aro_tech
aro_tech

Reputation: 1143

Unable to read post form value in Golang with htprouter

I'm new to Golang and trying to get a basic http app running using the httprouter API. I've hit a wall with reading posted form data, despite following the advice given in another StackOverflow question.

Here's my code (minus irrelevancies):

import (
    "fmt"
    "net/http"
    "github.com/julienschmidt/httprouter"
)


func main() {
    r := httprouter.New()
    r.POST("/sub", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        r.Header.Set("content-type", "text/html")
        err := r.ParseForm()
        if err != nil {
            fmt.Fprintf(w, "<h1>Error: %s</h1>\n", err)
        }
        fmt.Fprintf(w, "<h1>Submitted message!</h1>\n<p>-%s-</p>\n", r.PostFormValue("msg"))
    })
    http.ListenAndServe("localhost:3000", r)
}

In the output, where I should see -hello-, I just see --. When I inspect the http request in Firefox, in the Form Data panel, I see msg:"hello", so why is r.PostFormValue("msg") returning a blank string?

Upvotes: 0

Views: 1123

Answers (1)

aro_tech
aro_tech

Reputation: 1143

Thanks to Volker for pointing out an error. When I commented out the line r.Header.Set("content-type", "text/html"), the problem was resolved. Perhaps that was the issue, or perhaps there was some issue with the IDE (LiteIDE) caching an old version of the code. In any case, I can now read the posted value.

Upvotes: 1

Related Questions