我正在尝试在 go 中提交和解析表单,但无法正确解析表单字段。这是我正在尝试的代码的摘录。formtest.go : 包主import ( "fmt" "log" "net/http" "github.com/codegangsta/negroni" "github.com/davecgh/go-spew/spew" "github.com/julienschmidt/httprouter" "github.com/mholt/binding" "gopkg.in/unrolled/render.v1")type FormInfo struct { Fields []string Action string PageTitle string Id string}func (f *FormInfo) FieldMap(*http.Request) binding.FieldMap { return binding.FieldMap{ &f.Fields: "fields", &f.Action: "action", }}func formtest( resp http.ResponseWriter, req *http.Request, p httprouter.Params) { // var ticket Ticket info := new(FormInfo) tkt := p.ByName("tkt") info.PageTitle = tkt info.Id = tkt if req.Method == "POST" { bind_err := binding.Bind(req, info) if bind_err.Handle(resp) { log.Println("Error decoding form contents") return } spew.Dump(info) } Render.HTML(resp, http.StatusOK, "formtest", info) return}var Render *render.Renderfunc main() { router := httprouter.New() router.GET("/formtest", formtest) router.POST("/formtest", formtest) Render = render.New(render.Options{ Layout: "layout", IndentJSON: true, IndentXML: true, HTMLContentType: "text/html", IsDevelopment: true, }) n := negroni.New( negroni.NewRecovery(), negroni.NewLogger(), negroni.NewStatic(http.Dir("static")), ) n.UseHandler(router) n.Run(fmt.Sprintf(":%d", 3000))}
1 回答
函数式编程
TA贡献1807条经验 获得超9个赞
绑定所以不起作用。表单的字段 - name = "fields [1]" 和 name = "fields [0]" 彼此独立,因此对于它们中的每一个,您的结构都应包含自己的字段:
type FormInfo struct {
Fields1 string
Fields2 string
Action string
PageTitle string
Id string
}
分别在处理程序中:
...
&f.Fields1: "fields[0]",
&f.Fields2: "fields[1]",
&f.Action: "action",
...
结果,输出将是:
(*main.FormInfo)(0xc08200aa50)({
Fields1: (string) (len=7) "value 1",
Fields2: (string) (len=7) "value 2",
Action: (string) (len=4) "save",
PageTitle: (string) "",
Id: (string) ""
})
编辑:
如果您更改表单上的代码
...
<input type="text" name="fields"...
<input type="text" name="fields"...
你可以得到
info.Fields = [value 1 value 2]
无需更改其原始代码。
- 1 回答
- 0 关注
- 186 浏览
添加回答
举报
0/150
提交
取消