Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request.Post array empty upon form submission

Tags:

go

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>
`
like image 537
rputikar Avatar asked Dec 08 '12 18:12

rputikar


1 Answers

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)
}
like image 136
masebase Avatar answered Oct 15 '22 20:10

masebase