英文:
request.Post array empty upon form submission
问题
我正在尝试在Go中处理一个简单的HTML表单。然而,我无法在提交后获取任何POST数据。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>
`
英文:
I am trying to process a simple html form in go. However, I am unable to get any post data upon submission. The r.Form map is always []. Don't know where I am going wrong.
Thanks in advance.
Here is the code 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>
`
答案1
得分: 17
看起来你需要先调用ParseForm。来自go文档
// Form包含解析的表单数据,包括URL字段的查询参数和POST或PUT表单数据。
// 只有在调用ParseForm之后才能使用此字段。
// HTTP客户端忽略Form并使用Body代替。
Form url.Values
以下是一些使你的示例工作的代码。
func formHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
//处理错误,例如http.Error()
return
}
log.Println(r.Form)
rootHandler(w, r)
}
英文:
Looks like you need to call ParseForm first. From the go docs
// 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
And some code to get your example working.
func formHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
//handle error http.Error() for example
return
}
log.Println(r.Form)
rootHandler(w, r)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论