forked from h2non/imaginary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source_body.go
63 lines (49 loc) · 1.19 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
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 == 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 readRawBody(r *http.Request) ([]byte, error) {
return ioutil.ReadAll(r.Body)
}
func init() {
RegisterSource(ImageSourceTypeBody, NewBodyImageSource)
}