How to extract URL Query Parameters in Go

When an HTTP request is made to a server, it is sometimes necessary to extract certain predefined query parameters from the request URL in order to read the values. For example, given the following request:

$ curl "https://localhost:3000?id=abcdefghi"

Here’s how to get the value of the id query parameter on a Go server:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		id := r.URL.Query().Get("id")
		fmt.Println("id =>", id)
	})
	http.ListenAndServe(":3000", nil)
}
Output
id => abcdefghi

If you want to iterate over all the query parameters sent as part of a request, you can use the following code snippet:

values := r.URL.Query()
for k, v := range values {
	fmt.Println(k, " => ", v)
}

Thanks for reading, and happy coding!