Go/Golang Read Query String

Kevin FOO
Dec 2, 2020

--

The example below uses gorilla/mux package

package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)

func YourHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println("one=" + vars["one"])
log.Println("two=" + vars["two"])
query := r.URL.Query()
log.Println(query["three"])
log.Println(query["four"])
log.Println("four[0]=" + query["four"][0])
log.Println("four[1]=" + query["four"][1])
log.Println(query["five"])
fmt.Fprintf(w,"Gorilla!\n")
}

func main() {
r := mux.NewRouter()
r.HandleFunc("/{one}/{two}", YourHandler)
log.Fatal(http.ListenAndServe(":8000", r))
}

With the codes above, try browsing it with this URL with your browser

http://localhost:8000/1/2?three=3&four=9&four=8

Or curl it from terminal

curl 'http://localhost:8000/1/2?three=3&four=9&four=8'

Your should see the following in your web server console.

Variable one and two is only available if you declare it here.

r.HandleFunc("/{one}/{two}", YourHandler)

Variable three returns with an array of a value 3.

Variable four returns with an array of 2 values 8 and 9.

Variable five which is missing in the URL returns with an empty array.

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.

No responses yet