forked from h2non/imaginary
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsource_body.go
More file actions
92 lines (72 loc) · 1.83 KB
/
source_body.go
File metadata and controls
92 lines (72 loc) · 1.83 KB
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
package main
import (
"encoding/base64"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
)
const formFieldName = "file"
const maxMemory int64 = 1024 * 1024 * 64
const ImageSourceTypeBody ImageSourceType = "payload"
type BodyImageSource struct {
Config *SourceConfig
}
func NewBodyImageSource(config *SourceConfig) ImageSource {
return &BodyImageSource{config}
}
func (s *BodyImageSource) Matches(r *http.Request) bool {
return r.Method == http.MethodPost || r.Method == http.MethodPut
}
func (s *BodyImageSource) GetImage(r *http.Request) ([]byte, error) {
if isFormBody(r) {
return readFormBody(r)
}
return readRawBody(r)
}
func isFormBody(r *http.Request) bool {
return strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/")
}
func readFormBody(r *http.Request) ([]byte, error) {
err := r.ParseMultipartForm(maxMemory)
if err != nil {
return nil, err
}
file, _, err := r.FormFile(formFieldName)
if err != nil {
return nil, err
}
defer file.Close()
buf, err := ioutil.ReadAll(file)
if len(buf) == 0 {
err = ErrEmptyBody
}
return buf, err
}
func isJSONBody(r *http.Request) bool {
return strings.HasPrefix(r.Header.Get("Content-Type"), "application/json")
}
func readJSONBodyData(data []byte) ([]byte, error) {
type supportedJSONField struct {
Base64 string `json:"base64"`
}
jsonField := new(supportedJSONField)
if err := json.Unmarshal(data, jsonField); err != nil {
return nil, err
}
if jsonField.Base64 != "" {
base64Str := jsonField.Base64
base64Split := strings.Split(jsonField.Base64, "base64,")
if len(base64Split) > 1 {
base64Str = base64Split[1]
}
return base64.StdEncoding.DecodeString(base64Str)
}
return nil, ErrEmptyBody
}
func readRawBody(r *http.Request) ([]byte, error) {
return ioutil.ReadAll(r.Body)
}
func init() {
RegisterSource(ImageSourceTypeBody, NewBodyImageSource)
}