How to Extract URL Query Parameters in Go

Extracting query parameters from an URL is a common task when developing web services. For instance, to retrieve the id value from a request like:

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

You can use the following Go code:

go
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)
}

This results in:

output
id => abcdefghi

To loop through all query parameters in a request, the following approach can be utilized:

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

Thanks for reading, and happy coding!