Skip to content

Commit

Permalink
feat: support custom formvalue function
Browse files Browse the repository at this point in the history
  • Loading branch information
li-jin-gou committed Dec 10, 2022
1 parent f6aac90 commit 011607d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
34 changes: 34 additions & 0 deletions server.go
Expand Up @@ -1108,6 +1108,12 @@ func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error) {
//
// The returned value is valid until your request handler returns.
func (ctx *RequestCtx) FormValue(key string) []byte {
return defaultFormValue(ctx, key)
}

type FormValueFunc func(*RequestCtx, string) []byte

var defaultFormValue = func(ctx *RequestCtx, key string) []byte {
v := ctx.QueryArgs().Peek(key)
if len(v) > 0 {
return v
Expand All @@ -1126,6 +1132,34 @@ func (ctx *RequestCtx) FormValue(key string) []byte {
return nil
}

// SetCustomFormValueFunc sets FormValue function implementation to get form value.
func SetCustomFormValueFunc(f FormValueFunc) {
defaultFormValue = f
}

// SetNetHttpFormValueFunc sets FormValue function implementation to get form value.
// Consistent behaviour with net/http. POST and PUT body parameters take precedence over URL query string values.
func SetNetHttpFormValueFunc() {
SetCustomFormValueFunc(func(ctx *RequestCtx, key string) []byte {
v := ctx.PostArgs().Peek(key)
if len(v) > 0 {
return v
}
mf, err := ctx.MultipartForm()
if err == nil && mf.Value != nil {
vv := mf.Value[key]
if len(vv) > 0 {
return []byte(vv[0])
}
}
v = ctx.QueryArgs().Peek(key)
if len(v) > 0 {
return v
}
return nil
})
}

// IsGet returns true if request method is GET.
func (ctx *RequestCtx) IsGet() bool {
return ctx.Request.Header.IsGet()
Expand Down
16 changes: 16 additions & 0 deletions server_test.go
Expand Up @@ -1713,6 +1713,22 @@ func TestRequestCtxFormValue(t *testing.T) {
}
}

func TestSetStandardFormValueFunc(t *testing.T) {
t.Parallel()
SetNetHttpFormValueFunc()
var ctx RequestCtx
var req Request
req.SetRequestURI("/foo/bar?aaa=bbb")
req.SetBodyString("aaa=port")
req.Header.SetContentType("application/x-www-form-urlencoded")

ctx.Init(&req, nil, nil)

v := ctx.FormValue("aaa")
if string(v) != "port" {
t.Fatalf("unexpected value %q. Expecting %q", v, "port")
}
}
func TestRequestCtxUserValue(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 011607d

Please sign in to comment.