forms - 使用绑定(bind)解析数组表单元素

标签 forms parsing go binding

我正尝试在 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.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))

}

模板/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>

模板/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>

程序:

  1. 去运行 formtest.go
  2. 打开浏览器并转到http://127.0.0.1:3000/formtest
  3. 提交表格
  4. 检查控制台的日志。

观察:

(*main.FormInfo)(0xc820066c30)({
 Fields: ([]string) <nil>,
 Action: (string) (len=4) "save",
 PageTitle: (string) "",
 Id: (string) ""
})

期望:

Fields: ([]string) <contains two values submitted>,

但是当我尝试打印 Fields 的内容时,它是零。 我做错了什么?

最佳答案

绑定(bind)所以不起作用。您的表单字段 - name = "fields [1]"和 name = "fields [0]"彼此独立,因此对于它们中的每一个,您的结构都应包含自己的字段:

type FormInfo struct {
    Fields1   string
    Fields2   string
    Action    string
    PageTitle string
    Id        string
}

分别在handler中:

...
&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]

不改变其原始代码。

关于forms - 使用绑定(bind)解析数组表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32815561/

相关文章:

javascript - 使用 AngularJS 将表单发布到新窗口

javascript - 在不知道 ID 的情况下将焦点设置在动态创建的输入字段上

algorithm - 递归下降优先级解析——匹配较低优先级的前缀表达式

java - 解析UDP数据包后输出垃圾

json - 如何在 Go json marshal 中显示空对象而不是空结构或 nil

go - 缓冲区为空后关闭 "worker"go routine

type-conversion - 如何在 Go 中将 [4]uint8 转换为 uint32?

javascript - 即使必填字段无效, Angular 表单验证也允许提交

parsing - 如何用Scheme解析YAML?

javascript - 使用 Javascript 连接文本框