使用绑定解析数组表单元素

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


}


四季花海
浏览 187回答 1
1回答

函数式编程

绑定所以不起作用。表单的字段 - name = "fields [1]" 和 name = "fields [0]" 彼此独立,因此对于它们中的每一个,您的结构都应包含自己的字段:type FormInfo struct {&nbsp; &nbsp; Fields1&nbsp; &nbsp;string&nbsp; &nbsp; Fields2&nbsp; &nbsp;string&nbsp; &nbsp; Action&nbsp; &nbsp; string&nbsp; &nbsp; PageTitle string&nbsp; &nbsp; Id&nbsp; &nbsp; &nbsp; &nbsp; string}分别在处理程序中:...&f.Fields1: "fields[0]",&f.Fields2: "fields[1]",&f.Action:&nbsp; "action",...结果,输出将是:(*main.FormInfo)(0xc08200aa50)({&nbsp;Fields1: (string) (len=7) "value 1",&nbsp;Fields2: (string) (len=7) "value 2",&nbsp;Action: (string) (len=4) "save",&nbsp;PageTitle: (string) "",&nbsp;Id: (string) ""})编辑:如果您更改表单上的代码...<input type="text" name="fields"...<input type="text" name="fields"...你可以得到info.Fields = [value 1 value 2]无需更改其原始代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go