go-macaron / binding

Package binding is a middleware that provides request data binding and validation for Macaron.
Apache License 2.0
23 stars 17 forks source link

binding: support parse URL parameters into struct fields #32

Closed xmh19936688 closed 4 years ago

xmh19936688 commented 4 years ago

support args in url like '/path/:ID ' can be bind into struct

unknwon commented 4 years ago

Thanks for the PR!

Unfortunately, I do not think it fits the use cases of this package, which is used for form/content binding.

xmh19936688 commented 4 years ago

How about make the funcs variable? Then developers can customize them as macaron.ReturnHandler. Like this:

+type BindHandler func(formStruct interface{}, ifacePtr ...interface{}) macaron.Handler

+var (
+   FormBindHandler          BindHandler = Form
+   MultipartFormBindHandler BindHandler = MultipartForm
+   JsonBindHandler          BindHandler = Json
+)

func bind(ctx *macaron.Context, obj interface{}, ifacePtr ...interface{}) {
    contentType := ctx.Req.Header.Get("Content-Type")
    if ctx.Req.Method == "POST" || ctx.Req.Method == "PUT" || ctx.Req.Method == "PATCH" || ctx.Req.Method == "DELETE" {
        switch {
        case strings.Contains(contentType, "form-urlencoded"):
-           ctx.Invoke(Form(obj, ifacePtr...))
+           ctx.Invoke(FormBindHandler(obj, ifacePtr...))
        case strings.Contains(contentType, "multipart/form-data"):
-           ctx.Invoke(MultipartForm(obj, ifacePtr...))
+           ctx.Invoke(MultipartFormBindHandler(obj, ifacePtr...))
        case strings.Contains(contentType, "json"):
-           ctx.Invoke(Json(obj, ifacePtr...))
+           ctx.Invoke(JsonBindHandler(obj, ifacePtr...))
        default:
            var errors Errors
            if contentType == "" {
                errors.Add([]string{}, ERR_CONTENT_TYPE, "Empty Content-Type")
            } else {
                errors.Add([]string{}, ERR_CONTENT_TYPE, "Unsupported Content-Type")
            }
            ctx.Map(errors)
            ctx.Map(obj) // Map a fake struct so handler won't panic.
        }
    } else {
-       ctx.Invoke(Form(obj, ifacePtr...))
+       ctx.Invoke(FormBindHandler(obj, ifacePtr...))
    }
}
unknwon commented 4 years ago

Hmm, thanks for the brainstorming! I'm very cautious to add global variables recently.

What about adding another top level function binding.URL(...), which specifically binds URL parameters to a struct? Which seems minimum work for both this package and users.

unknwon commented 4 years ago

Thanks for the update, one last issue commented :)