-
Notifications
You must be signed in to change notification settings - Fork 3
/
odt.go
72 lines (62 loc) · 1.59 KB
/
odt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"archive/zip"
"io"
"os"
"path/filepath"
"text/template"
"time"
)
func writeHeader(archive *zip.Writer, filename string) (io.Writer, error) {
header := &zip.FileHeader{
Name: filename,
Method: zip.Store,
ModifiedTime: uint16(time.Now().UnixNano()),
ModifiedDate: uint16(time.Now().UnixNano()),
}
writer, err := archive.CreateHeader(header)
if err != nil {
return nil, err
}
return writer, nil
}
func addFileToArchive(archive *zip.Writer, source string, filename string) error {
writer, err := writeHeader(archive, filename)
if err != nil {
return err
}
file, err := os.Open(filepath.Join(source, filename))
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
if err != nil {
return err
}
return nil
}
func addTemplatedFileToArchive(archive *zip.Writer, source string, filename string, url string) error {
writer, err := writeHeader(archive, filename)
if err != nil {
return err
}
t := template.Must(template.New("template").ParseFiles(filepath.Join(source, filename)))
params := struct{ Url string }{Url: url}
err = t.ExecuteTemplate(writer, "document", params)
return err
}
func generateODT(writer io.Writer, source string, url string) error {
archive := zip.NewWriter(writer)
defer archive.Close()
if err := addFileToArchive(archive, source, "mimetype"); err != nil {
return err
}
if err := addFileToArchive(archive, source, "META-INF/manifest.xml"); err != nil {
return err
}
if err := addTemplatedFileToArchive(archive, source, "content.xml", url); err != nil {
return err
}
return nil
}