Search code examples
gomiddlewarego-alice

HTTP Router and Middleware


I'm using Julien Schmidt's router for GoLang and trying to get it working with Alice to chain middleware. I'm getting this error:

cannot use commonHandlers.ThenFunc(final) (type http.Handler) as type httprouter.Handle in argument to router.GET

and I'm not quite sure why.

My code is:

package main

import (
  "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
  "github.com/justinas/alice"
    "gopkg.in/mgo.v2"
    //"gopkg.in/mgo.v2/bson"
)


func middlewareOne(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    log.Println("Executing middlewareOne")
    next.ServeHTTP(w, r)
    log.Println("Executing middlewareOne again")
  })
}

func middlewareTwo(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    log.Println("Executing middlewareTwo")
    if r.URL.Path != "/" {
      return
    }
    next.ServeHTTP(w, r)
    log.Println("Executing middlewareTwo again")
  })
}

func final(w http.ResponseWriter, r *http.Request) {
  log.Println("Executing finalHandler")
  w.Write([]byte("OK"))
}

func main() {
    session, err := mgo.Dial("conn-string")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)

    commonHandlers := alice.New(middlewareOne, middlewareTwo)

    router := httprouter.New()
    router.GET("/", commonHandlers.ThenFunc(final))

    http.ListenAndServe(":5000", router)
}

Solution

  • httprouter's router.GET works only with httprouter.Handle type. Use the Handler method with http.Handler:

    router.Handler("GET", "/", commonHandlers.ThenFunc(final))