Go/Golang Read Query String

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.

Image for post
Image for post

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

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store