Gorilla is a web toolkit for the Go programming language. The gorilla/mux implements a request router and dispatcher for matching incomings requests to the respective handlers.
One of the cool feature it has is that the registered URLs can be built or reversed which helps maintaining the references to resources and nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes.
// Author: Rishijeet Mishrapackagemainimport("net/http""encoding/json""log""github.com/gorilla/mux")funcmain(){router:=mux.NewRouter()// Routes consist of a path and a handler function.router.HandleFunc("/myhandler",MyHandler)// Bind to a port and pass our router inlog.Fatal(http.ListenAndServe(":5000",router))}funcMyHandler(whttp.ResponseWriter,r*http.Request){//w.Write([]byte("The page to be rendered"))w.Header().Set("Content-Type","application/json")json.NewEncoder(w).Encode(struct{keystring}{"value"})}
Let’s add the POST method
12345678910111213
// Add the router.HandleFunc("/add/{item}",addItem).Methods("POST")//Add the funcfuncaddItem(whttp.ResponseWriter,r*http.Request){itemholder:=mux.Vars(r)['item']data=append(data,itemholder)json.NewEncoder(w).Encode(data)}
Let’s add the GET
1234567891011121314151617181920
// The struct for groupingtypeItemstruct{Datastring}vardata[]Item=[]Item{}funcaddItem(whttp.ResponseWriter,r*http.Request){varlatestItemItemjson.NewDecoder(r.Body).Decode(&latestItem)data=append(data,latestItem)// output the jsonw.Header().Set("Content-Type","application/json")json.NewEncoder(w).Encode(data)}
Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler.
123456
type MiddlewareFunc func(http.Handler) http.Handler
//Add the middleware to the route
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(loggingMiddleware)