From 1fa49addf164e0b28840c372cdeca2a1a266eb5c Mon Sep 17 00:00:00 2001 From: ^_^void Date: Tue, 25 Feb 2020 20:32:30 +0800 Subject: [PATCH] binding: support parse URL parameters into struct fields (#32) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * bind data support args in url support args in url like '/apth/:ID ' can be bind into struct * add URL() for binding data from url add URL() for binding data from url * Update binding.go * Update go.mod * Update binding.go * Update binding.go Co-authored-by: ᴜɴᴋɴᴡᴏɴ --- binding.go | 19 +++++++++++++++++++ go.mod | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/binding.go b/binding.go index de98478..014ab26 100644 --- a/binding.go +++ b/binding.go @@ -211,6 +211,25 @@ func Json(jsonStruct interface{}, ifacePtr ...interface{}) macaron.Handler { } } +// URL is the middleware to parse URL parameters into struct fields. +func URL(obj interface{}, ifacePtr ...interface{}) macaron.Handler { + return func(ctx *macaron.Context) { + var errors Errors + + ensureNotPointer(obj) + obj := reflect.New(reflect.TypeOf(obj)) + + val := obj.Elem() + for k, v := range ctx.AllParams() { + field := val.FieldByName(k[1:]) + if field.IsValid() { + errors = setWithProperType(field.Kind(), v, field, k, errors) + } + } + validateAndMap(obj, ctx, errors, ifacePtr...) + } +} + // RawValidate is same as Validate but does not require a HTTP context, // and can be used independently just for validation. // This function does not support Validator interface. diff --git a/go.mod b/go.mod index 6783abc..220cad6 100644 --- a/go.mod +++ b/go.mod @@ -6,5 +6,5 @@ require ( github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e golang.org/x/tools v0.0.0-20190805222050-c5a2fd39b72a // indirect - gopkg.in/macaron.v1 v1.3.4 + gopkg.in/macaron.v1 v1.3.5 )