-
Notifications
You must be signed in to change notification settings - Fork 64
/
multipart_related.go
56 lines (48 loc) · 1.24 KB
/
multipart_related.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
package openapi
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"regexp"
)
type MultipartRelatedBinding struct{}
func (MultipartRelatedBinding) Name() string {
return "json"
}
func (MultipartRelatedBinding) Bind(req *http.Request, obj interface{}) error {
b, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
return Deserialize(obj, b, req.Header.Get("Content-Type"))
}
func (MultipartRelatedBinding) BindBody(body []byte, obj interface{}) error {
re, _ := regexp.Compile(`--([a-zA-Z0-9+\-_]+)--`)
submatch := re.FindSubmatch(body)
if len(submatch) < 1 {
return errors.New("cannot parse multipart boundary")
}
return Deserialize(obj, body, "multipart/related; boundary="+string(submatch[1]))
}
type MultipartRelatedRender struct {
Data interface{}
contentType string
}
func (r MultipartRelatedRender) Render(w http.ResponseWriter) (err error) {
payloadBuf := &bytes.Buffer{}
ct, err := MultipartEncode(r.Data, payloadBuf)
if err != nil {
panic(err)
}
r.contentType = ct
w.Header().Set("Content-Type", r.contentType)
_, err = payloadBuf.WriteTo(w)
if err != nil {
panic(err)
}
return
}
func (r MultipartRelatedRender) WriteContentType(w http.ResponseWriter) {
w.Header().Set("Content-Type", r.contentType)
}