github.com/bytedance/go-tagexpr@v2.7.5-0.20210114074101-de5b8743ad85+incompatible/binding/request.go (about) 1 package binding 2 3 import ( 4 "bytes" 5 "io" 6 "net/http" 7 "net/url" 8 ) 9 10 type Request interface { 11 GetMethod() string 12 GetQuery() url.Values 13 GetContentType() string 14 GetHeader() http.Header 15 GetCookies() []*http.Cookie 16 GetBody() ([]byte, error) 17 GetPostForm() (url.Values, error) 18 GetForm() (url.Values, error) 19 } 20 21 func wrapRequest(req *http.Request) Request { 22 r := &httpRequest{ 23 Request: req, 24 } 25 if getBodyCodec(r) == bodyForm && req.PostForm == nil { 26 b, _ := r.GetBody() 27 if b != nil { 28 req.ParseMultipartForm(defaultMaxMemory) 29 } 30 } 31 return r 32 } 33 34 type httpRequest struct { 35 *http.Request 36 } 37 38 func (r *httpRequest) GetMethod() string { 39 return r.Method 40 } 41 func (r *httpRequest) GetQuery() url.Values { 42 return r.URL.Query() 43 } 44 45 func (r *httpRequest) GetContentType() string { 46 return r.GetHeader().Get("Content-Type") 47 } 48 49 func (r *httpRequest) GetHeader() http.Header { 50 return r.Header 51 } 52 53 func (r *httpRequest) GetCookies() []*http.Cookie { 54 return r.Cookies() 55 } 56 57 func (r *httpRequest) GetBody() ([]byte, error) { 58 body, _ := r.Body.(*Body) 59 if body != nil { 60 body.Reset() 61 return body.bodyBytes, nil 62 } 63 switch r.Method { 64 case "POST", "PUT", "PATCH", "DELETE": 65 var buf bytes.Buffer 66 _, err := io.Copy(&buf, r.Body) 67 r.Body.Close() 68 if err != nil { 69 return nil, err 70 } 71 body = &Body{ 72 Buffer: &buf, 73 bodyBytes: buf.Bytes(), 74 } 75 r.Body = body 76 return body.bodyBytes, nil 77 default: 78 return nil, nil 79 } 80 } 81 82 func (r *httpRequest) GetPostForm() (url.Values, error) { 83 return r.PostForm, nil 84 } 85 86 func (r *httpRequest) GetForm() (url.Values, error) { 87 return r.Form, nil 88 }