Monday, July 7, 2014

Gorilla Mux and multiple routers

Looking at Gorilla's Mux, I wanted to come up with a simple example of how to bind multiple routers to different base URLs.  For the first router, I'm not using the PathPrefix() method, so the handler function must contain the prefix that you're interested ('/v1').  The second doesn't require that as we're using the Subrouter() that utilizes the prefix for all handlers.


package main

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

func main() {
    rtr := mux.NewRouter()
    rtr.HandleFunc("/v1/user/{name:[a-z]+}/profile", profile).Methods("GET")

    rtrv2 := mux.NewRouter().PathPrefix("/v2").Subrouter()
    rtrv2.HandleFunc("/user/{name:[a-z]+}/profile", profilev2).Methods("GET")
 

    http.Handle("/v1/", rtr)    // need trailing slash     
    http.Handle("/v2/", rtrv2)  // need trailing slash

    log.Println("Listening...")
    http.ListenAndServe(":3000", nil)
}

func profile(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    name := params["name"]
    w.Write([]byte("Hello " + name))
}

func profilev2(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    name := params["name"]
    w.Write([]byte("Goodbye " + name))
}