From 74352e9b4d11c832fc822b627aba2c482a82047b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BA=90=E6=96=87=E9=9B=A8?= <41315874+fumiama@users.noreply.github.com> Date: Thu, 9 Feb 2023 14:29:32 +0800 Subject: [PATCH] feat: pack use io.Copy --- pack.go | 41 +++++++++++++++++++++++------------------ structdoc_test.go | 7 +++++-- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/pack.go b/pack.go index 6801db3..2bbe513 100644 --- a/pack.go +++ b/pack.go @@ -2,8 +2,9 @@ package docxlib import ( "archive/zip" - "bytes" "encoding/xml" + "io" + "os" ) // This receives a zip file writer (word documents are a zip with multiple xml inside) @@ -18,30 +19,24 @@ func (f *Docx) pack(zipWriter *zip.Writer) (err error) { "word/styles.xml", "[Content_Types].xml", } - files := make(map[string][]byte, 64) + files := make(map[string]io.Reader, 64) for _, name := range fileslst { - files[name], err = TEMP_XML_FS.ReadFile("xml/" + name) + files[name], err = TEMP_XML_FS.Open("xml/" + name) if err != nil { return } } - files["word/_rels/document.xml.rels"], err = marshal(f.DocRelation) - if err != nil { - return - } - files["word/document.xml"], err = marshal(f.Document) - if err != nil { - return - } + files["word/_rels/document.xml.rels"] = marshaller{data: f.DocRelation} + files["word/document.xml"] = marshaller{data: f.Document} - for path, data := range files { + for path, r := range files { w, err := zipWriter.Create(path) if err != nil { return err } - _, err = w.Write(data) + _, err = io.Copy(w, r) if err != nil { return err } @@ -50,13 +45,23 @@ func (f *Docx) pack(zipWriter *zip.Writer) (err error) { return } -func marshal(data interface{}) (out []byte, err error) { - buf := bytes.NewBuffer(make([]byte, 0, 1024)) - buf.WriteString(xml.Header) - err = xml.NewEncoder(buf).Encode(data) +type marshaller struct { + data interface{} + io.Reader + io.WriterTo +} + +// Read is fake and is to trigger io.WriterTo +func (m marshaller) Read(p []byte) (n int, err error) { + return 0, os.ErrInvalid +} + +// WriteTo n is always 0 for we don't care that value +func (m marshaller) WriteTo(w io.Writer) (n int64, err error) { + _, err = io.WriteString(w, xml.Header) if err != nil { return } - out = buf.Bytes() + err = xml.NewEncoder(w).Encode(m.data) return } diff --git a/structdoc_test.go b/structdoc_test.go index 1d8bb4e..9d56bfa 100644 --- a/structdoc_test.go +++ b/structdoc_test.go @@ -575,10 +575,13 @@ func TestMarshalDrawingStructure(t *testing.T) { nextPara := w.AddParagraph() nextPara.AddLink("google", `http://google.com`) - doc, err := marshal(w.Document) + f, err := os.Create("test.xml") + if err != nil { + t.Fatal(err) + } + _, err = marshaller{data: w.Document}.WriteTo(f) if err != nil { t.Fatal(err) } - os.WriteFile("test.xml", doc, 0644) t.Fail() }