HTTP router and middleware

I am using Julien Schmidt router for GoLang and am trying to get it to work with Alice to bundle middleware. I am getting this error:

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

and I don't quite understand why.

My code:

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)
}

      

+3


source to share


1 answer


httprouter router.GET

only works with httprouter.Handle

. Use Handler

with http.Handler

:



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

      

+6


source







All Articles