request.Post数组在提交表单后为空

我正在尝试处理一个简单的html表单。但是,提交后我无法获得任何帖子数据。r.Form映射始终为[]。不知道我要去哪里错了。


提前致谢。


这是代码http://play.golang.org/p/aZxPCcRAVV


package main


import (

    "html/template"

    "log"

    "net/http"

)


func rootHandler(w http.ResponseWriter, r *http.Request) {

    t, _ := template.New("form.html").Parse(form)

    t.Execute(w, "")

}


func formHandler(w http.ResponseWriter, r *http.Request) {

    log.Println(r.Form)

    rootHandler(w, r)

}


func main() {

    http.HandleFunc("/", rootHandler)

    http.HandleFunc("/login", formHandler)

    http.ListenAndServe("127.0.0.1:9999", nil)

}


var form = `

<h1>Login</h1>

<form action="/login" method="POST">

<div><input name="username" type="text"></div>

<div><input type="submit" value="Save"></div>

</form>

`


炎炎设计
浏览 264回答 1
1回答

隔江千里

看来您需要先调用ParseForm。随时随地的文档// Form contains the parsed form data, including both the URL// field's query parameters and the POST or PUT form data.// This field is only available after ParseForm is called.// The HTTP client ignores Form and uses Body instead.Form url.Values还有一些代码可以使您的示例正常工作。func formHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; err := r.ParseForm()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp;//handle error http.Error() for example&nbsp; &nbsp; &nbsp; &nbsp;return&nbsp; &nbsp; }&nbsp; &nbsp; log.Println(r.Form)&nbsp; &nbsp; rootHandler(w, r)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go