Skip to content

Commit 1fa49ad

Browse files
xmh19936688unknwon
andauthored
binding: support parse URL parameters into struct fields (#32)
* 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: ᴜɴᴋɴᴡᴏɴ <[email protected]>
1 parent d92aca2 commit 1fa49ad

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

binding.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,25 @@ func Json(jsonStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
211211
}
212212
}
213213

214+
// URL is the middleware to parse URL parameters into struct fields.
215+
func URL(obj interface{}, ifacePtr ...interface{}) macaron.Handler {
216+
return func(ctx *macaron.Context) {
217+
var errors Errors
218+
219+
ensureNotPointer(obj)
220+
obj := reflect.New(reflect.TypeOf(obj))
221+
222+
val := obj.Elem()
223+
for k, v := range ctx.AllParams() {
224+
field := val.FieldByName(k[1:])
225+
if field.IsValid() {
226+
errors = setWithProperType(field.Kind(), v, field, k, errors)
227+
}
228+
}
229+
validateAndMap(obj, ctx, errors, ifacePtr...)
230+
}
231+
}
232+
214233
// RawValidate is same as Validate but does not require a HTTP context,
215234
// and can be used independently just for validation.
216235
// This function does not support Validator interface.

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@ require (
66
github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337
77
github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e
88
golang.org/x/tools v0.0.0-20190805222050-c5a2fd39b72a // indirect
9-
gopkg.in/macaron.v1 v1.3.4
9+
gopkg.in/macaron.v1 v1.3.5
1010
)

0 commit comments

Comments
 (0)