在表单提交时,请 – 请求.Post数组为空

前端之家收集整理的这篇文章主要介绍了在表单提交时,请 – 请求.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>
`

解决方法

看来你需要先调用ParseForm.从go文档
// 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) {
    err := r.ParseForm()
    if err != nil {
       //handle error http.Error() for example
       return
    }
    log.Println(r.Form)
    rootHandler(w,r)
}
原文链接:https://www.f2er.com/html/224684.html

猜你在找的HTML相关文章