douliu7929 2012-12-08 18:20
浏览 129
已采纳

request.Post数组提交后为空

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条回答 默认 最新

  • dotdx80642 2012-12-08 18:41
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序