英文:
Parsing array form elements with bindings
问题
我正在尝试在Go中提交和解析一个表单,但无法正确解析表单字段。以下是我尝试的代码摘录。
formtest.go:
package main
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) {
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.Render
func 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))
}
templates/layout.tmpl:
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ .PageTitle }}</title>
<meta http-equiv="Content-Type" content="text/html;" charset="utf-8">
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/mobile.png" />
<meta name="viewport"
content="initial-scale=1.0,width=device-width,user-scalable=no">
<meta name="generator" content="Go">
<link rel="stylesheet" href="/base.css" type="text/css">
</head>
<body>
<div class="mainbody">
{{ yield }}
</div>
</body>
</html>
templates/formtest.tmpl:
<h1>{{ .PageTitle }}</h1>
<form action="/formtest/{{ .Id }}" method="POST">
<div class="details">
<label>Question 1</label>
<input type="text" name="fields[0]" value="value 1" />
</div>
<div class="details">
<label>Question 2</label>
<input type="text" name="fields[1]" value="value 2" />
</div>
<div class="details">
<input type="submit" name="action" value="save" />
</div>
</form>
步骤:
- 运行
go run formtest.go
- 打开浏览器,访问 http://127.0.0.1:3000/formtest
- 提交表单
- 检查控制台日志。
观察结果:
(*main.FormInfo)(0xc820066c30)({
Fields: ([]string) <nil>,
Action: (string) (len=4) "save",
PageTitle: (string) "",
Id: (string) ""
})
期望结果:
Fields: ([]string) <包含两个提交值>,
但是当我尝试打印 Fields 的内容时,它是 nil。我做错了什么?
英文:
I am trying to submit and parse a form in go and I am failing to parse the form fields properly.
Here is an excerpt of the code I am trying.
formtest.go :
package main
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.Render
func 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))
}
templates/layout.tmpl :
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ .PageTitle }}</title>
<meta http-equiv="Content-Type" content="text/html;" charset="utf-8">
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/mobile.png" />
<meta name="viewport"
content="initial-scale=1.0,width=device-width,user-scalable=no">
<meta name="generator" content="Go">
<link rel="stylesheet" href="/base.css" type="text/css">
</head>
<body>
<div class="mainbody">
{{ yield }}
</div>
</body>
</html>
templates/formtest.tmpl :
<h1>{{ .PageTitle }}</h1>
<form action="/formtest/{{ .Id }}" method="POST">
<div class="details">
<label>Question 1</label>
<input type="text" name="fields[0]" value="value 1" />
</div>
<div class="details">
<label>Question 2</label>
<input type="text" name="fields[1]" value="value 2" />
</div>
<div class="details">
<input type="submit" name="action" value="save" />
</div>
</form>
Procedure:
- go run formtest.go
- Open browser and go to http://127.0.0.1:3000/formtest
- Submit the form
- Check console for the logs.
Observation :
(*main.FormInfo)(0xc820066c30)({
Fields: ([]string) <nil>,
Action: (string) (len=4) "save",
PageTitle: (string) "",
Id: (string) ""
})
Expectation :
Fields: ([]string) <contains two values submitted>,
But when I try to print the contents of Fields, it is nil.
What am I doing wrong?
答案1
得分: 1
绑定不起作用。您表单的字段 - 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]
而无需更改其原始代码。
英文:
Binding so not work. The fields of your form - name = "fields [1]" and
name = "fields [0]" are independent from each other, so for each of them your structure should contain its own field:
type FormInfo struct {
Fields1 string
Fields2 string
Action string
PageTitle string
Id string
}
respectively, in the handler:
...
&f.Fields1: "fields[0]",
&f.Fields2: "fields[1]",
&f.Action: "action",
...
As a result, the output will be:
(*main.FormInfo)(0xc08200aa50)({
Fields1: (string) (len=7) "value 1",
Fields2: (string) (len=7) "value 2",
Action: (string) (len=4) "save",
PageTitle: (string) "",
Id: (string) ""
})
EDIT:
If you change the code in the form on the
...
<input type="text" name="fields"...
<input type="text" name="fields"...
you can get
info.Fields = [value 1 value 2]
without changing its original code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论