我正在尝试在 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))
}
函数式编程
相关分类