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>
`
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With