Rest API with Go & Gorilla Mux

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.

The routes can be declared as mentioned below

1
2
3
4
5
6
7
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/users", UsersHandler)
    r.HandleFunc("/blogs", BlogHandler)
    http.Handle("/", r)
}

The basic http server code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Author: Rishijeet Mishra
package main

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

func main() {
    router := mux.NewRouter()
    // Routes consist of a path and a handler function.
    router.HandleFunc("/myhandler", MyHandler)

    // Bind to a port and pass our router in
    log.Fatal(http.ListenAndServe(":5000", router))
}

func MyHandler(w http.ResponseWriter, r *http.Request){
    //w.Write([]byte("The page to be rendered"))
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(struct
    {
        key string
    }
    {
        "value"
    } )

}

Let’s add the POST method

1
2
3
4
5
6
7
8
9
10
11
12
13
// Add the route


r.HandleFunc("/add/{item}", addItem).Methods("POST")

//Add the func

func addItem(w http.ResponseWriter, r *http.Request){
    itemholder  := mux.Vars(r)['item']
    data = append( data, itemholder)
    json.NewEncoder(w).Encode(data)

}

Let’s add the GET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// The struct for grouping
type Item struct {
    Data string
}

var data []Item = []Item{}


func addItem(w http.ResponseWriter, r *http.Request){

    var latestItem Item
    json.NewDecoder(r.Body).Decode(&latestItem)

    data = append( data, latestItem)

    // output the json
    w.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.

1
2
3
4
5
6
type MiddlewareFunc func(http.Handler) http.Handler

//Add the middleware to the route
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(loggingMiddleware)

Click for more details on the gorilla/mux

Comments