How to retrieve parameter values in golang using net/http?

How to retrieve parameter values in golang using net/http?

In this post, I am going to show you how you can retrieve the parameter values of your HTTP requests using the standard library net/http in golang.

Although, there are web frameworks out there that you can use for your web application which will make your development much easier.

The standard library is so good that it's so hard to ignore it and use other frameworks.

Retrieving parameter values from GET requests

When retrieving parameters from GET requests there's a function that we can use and it is r.URL.Query().Get().

r.URL.Query.Get() is a function that takes a key to retrieve a value from a hashmap.

The example below will show us how to retrieve the value of the page query parameter.

func handleQueryParameters(w http.ResponseWriter, r *http.Request) {
    page := r.URL.Query().Get("page")
    log.Println(page)
}

Retrieving parameter values from POST requests

When retrieving parameters from POST requests there's a process that we will have to do.

In the beginning, we will have to parse the request using r.ParseForm() which will populate r.PostForm and r.Form. Both are being stored in hashmaps.

Furthermore, if we want to retrieve the value of the parameter we are going to use r.PostForm.Get().

r.PostForm.Get() is a function that takes a key to retrieve a value from a hashmap.

There's another method that we can use to retrieve parameter values which does r.ParseForm() for you but, I wouldn't recommend it because errors are ignored for it.

But if you are fine with errors ignored in r.ParseForm(), you may want to use it.

The function is called r.PostFormValue().

The example below will show us how to retrieve the value of the name body parameter.

func handlePOST(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        log.Fatalln("error")
    }
    name := r.PostForm.Get("name")
    log.Println(name)
}

Hey guys, thanks for reading this blog post I appreciate it.

If there's anything that needs fixing, please don't hesitate to contact me.

Thank you!

References

pkg.go.dev/net/http

stackoverflow.com/questions/15407719/in-gos..

stackoverflow.com/questions/16512009/how-to..