restgogorillamux

How to use an optional query parameter in Go gorilla/mux?


Probably there is already a solution here to my problem, but I couldn't find it anywhere. I tried a bunch of stuff, but nothing worked so far.

I have something like this:

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func HealthCheck(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprintln(w, "Healthy")
    // Also print the value of 'foo'
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/health-check", HealthCheck).Methods("GET").Queries("foo", "{foo}").Name("HealthCheck")
    r.HandleFunc("/health-check", HealthCheck).Methods("GET")
    http.ListenAndServe(":8080", r)
}

What I'm trying to achieve:

curl http://localhost:8080/health-check

Should respond with: Healthy <foo> ( -> the default value of foo)

And also the following:

curl http://localhost:8080/health-check?foo=bar

Should respond with: Healthy bar


Solution

  • One solution if to simply handle the query params in your handler:

    package main
    
    import (
        "net/http"
    
        "github.com/gorilla/mux"
    )
    
    func HealthCheckHandler(w http.ResponseWriter, req *http.Request) {
        values := req.URL.Query()
        foo := values.Get("foo")
    
        if foo != "" {
            w.Write([]byte("Healthy " + foo))
        } else {
            w.Write([]byte("Healthy <foo>"))
        }
        w.WriteHeader(http.StatusOK)
    }
    
    func main() {
        r := mux.NewRouter()
        r.HandleFunc("/health-check", HealthCheckHandler)
        http.ListenAndServe(":8080", r)
    }
    

    according to the gorilla/mux documentation, the Queries method is meant to match your handler to specific functions, akin to a regular expression.