This repository has been archived by the owner on Apr 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
document.go
102 lines (85 loc) · 2 KB
/
document.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package gotenberg
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
)
// Document reprents a file which
// will be send to the Gotenberg API.
type Document interface {
Filename() string
Reader() (io.ReadCloser, error)
}
type document struct {
filename string
}
func (doc *document) Filename() string {
return doc.filename
}
type documentFromPath struct {
fpath string
*document
}
// NewDocumentFromPath creates a Document from
// a file path.
func NewDocumentFromPath(filename, fpath string) (Document, error) {
if !fileExists(fpath) {
return nil, fmt.Errorf("%s: file %s does not exist", fpath, filename)
}
return &documentFromPath{
fpath,
&document{filename},
}, nil
}
func (doc *documentFromPath) Reader() (io.ReadCloser, error) {
in, err := os.Open(doc.fpath)
if err != nil {
return nil, fmt.Errorf("%s: opening file: %v", doc.Filename(), err)
}
return in, nil
}
type documentFromString struct {
data string
*document
}
// NewDocumentFromString creates a Document from
// a string.
func NewDocumentFromString(filename, data string) (Document, error) {
if len(data) == 0 {
return nil, fmt.Errorf("%s: string is empty", filename)
}
return &documentFromString{
data,
&document{filename},
}, nil
}
func (doc *documentFromString) Reader() (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader(doc.data)), nil
}
type documentFromBytes struct {
data []byte
*document
}
// NewDocumentFromBytes creates a Document from
// bytes.
func NewDocumentFromBytes(filename string, data []byte) (Document, error) {
if len(data) == 0 {
return nil, fmt.Errorf("%s: bytes are empty", filename)
}
return &documentFromBytes{
data,
&document{filename},
}, nil
}
func (doc *documentFromBytes) Reader() (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(doc.data)), nil
}
// Compile-time checks to ensure type implements desired interfaces.
var (
_ = Document(new(documentFromPath))
_ = Document(new(documentFromString))
_ = Document(new(documentFromBytes))
)