I'm playing around with Martini, and for some reason I can't get the contrib binding package to work.
My struct isn't having the values bound to. I've reduced the code down to it's simplest form, but it still doesn't work.
Can anyone see what I'm doing wrong?
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/binding"
"net/http"
)
var html string = `<form method="POST" enctype="application/x-www-form-urlencoded"><input name="un" type="text" /><input type="submit" value="Some button" /></form>`
type FormViewModel struct {
Username string `form: "un"`
}
func main() {
m := martini.Classic()
m.Get("/", func(w http.ResponseWriter) {
w.Header().Add("content-type", "text/html")
w.Write([]byte(html))
})
m.Post("/", binding.Form(FormViewModel{}), func(vm FormViewModel) string {
return "You entered: " + vm.Username
})
m.Run()
}
It is just a parsing issue in the definition of the tag associated to the field of the structure.
You need to remove the blank character after form:
If you write the structure as follows:
type FormViewModel struct {
Username string `form:"un"` // No blank after form:
}
... it should work better.
The Go language specification says:
By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.
Apparently, the parser implemented in the reflect package does not tolerate a space after the colon.