Reflectionless data binding for Go's net/http (not actively maintained)
Reflectionless data binding for Go's net/http (not actively maintained)
Reflectionless data binding for Go's net/http
net/http is present (Negroni, gocraft/web, std lib, etc.)……You can test from CLI using the excellent httpie client
http -f POST localhost:3000/upload data@myupload
You may optionally have your type implement the binding.Validator interface to perform your own data validation. The .Validate() method is called after the struct is populated.
func (cf ContactForm) Validate(req *http.Request) error {
if cf.Message == "Go needs generics" {
return binding.Errors{
binding.NewError([]string{"message"}, "ComplaintError", "Go has generics. They're called interfaces.")
}
}
return nil
}For types you've defined, you can bind form data to it by implementing the Binder interface. Here's a contrived example:
type MyBinder map[string]string
func (t MyBinder) Bind(fieldName string, strVals []string) error {
t["formData"] = strVals[0]
return nil
}If you can't add a method to the type, you can still specify a Binder func in the field spec. Here's a contrived example that binds an integer (not necessary, but you get the idea):
func (t *MyType) FieldMap(req *http.Request) binding.FieldMap {
return binding.FieldMap{
"a-key": binding.Field{
Form: "number",
Binder: func(fieldName string, formVals []string) error {
val, err := strconv.Atoi(formVals[0])
if err != nil {
return binding.Errors{binding.NewError([]string{fieldName}, binding.DeserializationError, err.Error())}
}
t.SomeNumber = val
return nil
},
},
}
}The Errors type has a convenience method, Add, which you can use to append to the slice if you prefer.
The following types are supported in form deserialization by default. (JSON requests are delegated to encoding/json.)
No open issues yet, or sync has not completed.