英文:
Martini binding doesn't appear to be working
问题
我正在玩Martini,但是出现了一些问题,无法让contrib binding包正常工作。
我的结构体没有绑定值。我已经将代码简化到最简形式,但仍然无法工作。
有人能看出我做错了什么吗?
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()
}
英文:
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()
}
答案1
得分: 1
这只是一个在与结构体字段相关的标签定义中的解析问题。
你需要在 form: 后面删除空格字符。
如果你将结构体定义如下:
type FormViewModel struct {
Username string `form:"un"` // 在 form: 后面没有空格
}
...应该会工作得更好。
Go语言规范中说:
按照惯例,标签字符串是可选的以空格分隔的 key:"value" 对的串联。每个 key 是一个非空字符串,由非控制字符组成,除了空格(U+0020 ' ')、引号(U+0022 '"')和冒号(U+003A ':')。每个 value 使用 U+0022 '"' 字符和 Go 字符串字面值语法进行引用。
显然,在reflect包中实现的解析器不允许在冒号后面有空格。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论