2015-05-19 62 views
3

我正在爲GoLang使用Julien Schmidt的路由器,並試圖讓它與Alice合作來鏈接中間件。我得到這個錯誤:HTTP路由器和中間件

不能使用commonHandlers.ThenFunc(最終)(類型http.Handler)類型httprouter.Handle在爭論router.GET

,我不明白爲什麼。

我的代碼是:只有

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

非常感謝您! –

回答

5

httprouter的router.GET作品與httprouter.Handle類型。與http.Handler使用Handler方法:

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