forked from deepmap/oapi-codegen
/
file.go
71 lines (61 loc) · 1.29 KB
/
file.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
package types
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
)
type File struct {
multipart *multipart.FileHeader
data []byte
filename string
}
func (file *File) InitFromMultipart(header *multipart.FileHeader) {
file.multipart = header
file.data = nil
file.filename = ""
}
func (file *File) InitFromBytes(data []byte, filename string) {
file.data = data
file.filename = filename
file.multipart = nil
}
func (file File) MarshalJSON() ([]byte, error) {
b, err := file.Bytes()
if err != nil {
return nil, err
}
return json.Marshal(b)
}
func (file *File) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &file.data)
}
func (file File) Bytes() ([]byte, error) {
if file.multipart != nil {
f, err := file.multipart.Open()
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
return io.ReadAll(f)
}
return file.data, nil
}
func (file File) Reader() (io.ReadCloser, error) {
if file.multipart != nil {
return file.multipart.Open()
}
return io.NopCloser(bytes.NewReader(file.data)), nil
}
func (file File) Filename() string {
if file.multipart != nil {
return file.multipart.Filename
}
return file.filename
}
func (file File) FileSize() int64 {
if file.multipart != nil {
return file.multipart.Size
}
return int64(len(file.data))
}