forked from ariefsuharsono/imaginary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource_body.go
70 lines (55 loc) · 1.31 KB
/
source_body.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
package main
import (
"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 == "POST" || r.Method == "PUT"
}
func (s *BodyImageSource) GetImage(r *http.Request, o ServerOptions) ([]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("file")
if err != nil {
return nil, err
}
defer file.Close()
buf, err := ioutil.ReadAll(file)
if len(buf) == 0 {
err = ErrEmptyBody
}
return buf, err
}
func formField(r *http.Request) string {
if field := r.URL.Query().Get("field"); field != "" {
return field
}
return formFieldName
}
func readRawBody(r *http.Request) ([]byte, error) {
return ioutil.ReadAll(r.Body)
}
func init() {
RegisterSource(ImageSourceTypeBody, NewBodyImageSource)
}