Fragment Description:



This example, introduces the Gorilla mux Server usage.
A Mux struct extends the mux Server with Middlewares.
Note the Middleware Interface and its Apply function...
The Handle and HandleFunc chain.
Whenever a handler is called (here:
"/hello/{var}) a lot of middlewares can be started to elaborate complex responses).

httpChainingHandlers

Last update, on 2015, Fri 9 Oct, 16:15:37

/* ... <== see fragment description ... */

package main

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

type Middleware interface {
    Apply(http.Handler) http.Handler
}
type LoggingMiddleware struct {
    logger *log.Logger
}

func (l LoggingMiddleware) Apply(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        before := time.Now()
        l.logger.Printf("%v %v - %v", before, r.URL, r.RemoteAddr)
        next.ServeHTTP(w, r)
        after := time.Now()
        l.logger.Printf("%v %v - %v - %0.4f", after, r.URL, r.RemoteAddr, after.Sub(before).Seconds())
    })
}

type Mux struct {
    *mux.Router
    middlewares []Middleware
}

func NewMux() Mux {
    m := Mux{}
    m.Router = mux.NewRouter()
    return m
}
func (m Mux) Handle(pattern string, handler http.Handler) {
    for _, mw := range m.middlewares {
        handler = mw.Apply(handler)
    }
    m.Router.Handle(pattern, handler)
}
func (m Mux) HandleFunc(pattern string, handler http.HandlerFunc) {
    m.Handle(pattern, http.Handler(handler))
}
func main() {
    m := NewMux()
    l := LoggingMiddleware{log.New(os.Stdout, "[http] ", 0)}
    m.middlewares = append(m.middlewares, l)
    m.HandleFunc("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello %v", mux.Vars(r)["name"])
    })
    fmt.Println("Listening on port 3000:")
    http.ListenAndServe(":3000", m)
}

/*
Listening on port 3000:
[http] 2015-09-01 19:54:26.6339632 /hello/John - 127.0.0.1:58809
[http] 2015-09-01 19:54:26.6349633 /hello/John - 127.0.0.1:58809 - 0.0010
*/



Comments