1 Star 0 Fork 0

Go Ultra / Go Ultra Framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
requests.go 2.64 KB
一键复制 编辑 原始数据 按行查看 历史
vhake 提交于 2022-05-17 11:22 . init project
package httpx
import (
"io"
"net/http"
"strings"
"gitee.com/go-ultra/gou/core/mapping"
"gitee.com/go-ultra/gou/rest/internal/encoding"
"gitee.com/go-ultra/gou/rest/internal/header"
"gitee.com/go-ultra/gou/rest/pathvar"
)
const (
formKey = "form"
pathKey = "path"
maxMemory = 32 << 20 // 32MB
maxBodyLen = 8 << 20 // 8MB
separator = ";"
tokensInAttribute = 2
)
var (
formUnmarshaler = mapping.NewUnmarshaler(formKey, mapping.WithStringValues())
pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
)
// Parse parses the request.
func Parse(r *http.Request, v interface{}) error {
if err := ParsePath(r, v); err != nil {
return err
}
if err := ParseForm(r, v); err != nil {
return err
}
if err := ParseHeaders(r, v); err != nil {
return err
}
return ParseJsonBody(r, v)
}
// ParseHeaders parses the headers request.
func ParseHeaders(r *http.Request, v interface{}) error {
return encoding.ParseHeaders(r.Header, v)
}
// ParseForm parses the form request.
func ParseForm(r *http.Request, v interface{}) error {
if err := r.ParseForm(); err != nil {
return err
}
if err := r.ParseMultipartForm(maxMemory); err != nil {
if err != http.ErrNotMultipart {
return err
}
}
params := make(map[string]interface{}, len(r.Form))
for name := range r.Form {
formValue := r.Form.Get(name)
if len(formValue) > 0 {
params[name] = formValue
}
}
return formUnmarshaler.Unmarshal(params, v)
}
// ParseHeader parses the request header and returns a map.
func ParseHeader(headerValue string) map[string]string {
ret := make(map[string]string)
fields := strings.Split(headerValue, separator)
for _, field := range fields {
field = strings.TrimSpace(field)
if len(field) == 0 {
continue
}
kv := strings.SplitN(field, "=", tokensInAttribute)
if len(kv) != tokensInAttribute {
continue
}
ret[kv[0]] = kv[1]
}
return ret
}
// ParseJsonBody parses the post request which contains json in body.
func ParseJsonBody(r *http.Request, v interface{}) error {
if withJsonBody(r) {
reader := io.LimitReader(r.Body, maxBodyLen)
return mapping.UnmarshalJsonReader(reader, v)
}
return mapping.UnmarshalJsonMap(nil, v)
}
// ParsePath parses the symbols reside in url path.
// Like http://localhost/bag/:name
func ParsePath(r *http.Request, v interface{}) error {
vars := pathvar.Vars(r)
m := make(map[string]interface{}, len(vars))
for k, v := range vars {
m[k] = v
}
return pathUnmarshaler.Unmarshal(m, v)
}
func withJsonBody(r *http.Request) bool {
return r.ContentLength > 0 && strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
}
Go
1
https://gitee.com/go-ultra/gou.git
git@gitee.com:go-ultra/gou.git
go-ultra
gou
Go Ultra Framework
v0.0.1

搜索帮助