HTTP 路由器和中间件
HTTP Router and Middleware
我正在使用 Julien Schmidt 的 GoLang 路由器,并试图让它与 Alice 一起工作以链接中间件。我收到此错误:
不能在 router.GET[= 的参数中使用 commonHandlers.ThenFunc(final)(类型 http.Handler)作为类型 httprouter.Handle 11=]
我不太清楚为什么。
我的代码是:
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)
}
httprouter 的 router.GET
仅适用于 httprouter.Handle
type. Use the Handler
方法 http.Handler
:
router.Handler("GET", "/", commonHandlers.ThenFunc(final))
我正在使用 Julien Schmidt 的 GoLang 路由器,并试图让它与 Alice 一起工作以链接中间件。我收到此错误:
不能在 router.GET[= 的参数中使用 commonHandlers.ThenFunc(final)(类型 http.Handler)作为类型 httprouter.Handle 11=]
我不太清楚为什么。
我的代码是:
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)
}
httprouter 的 router.GET
仅适用于 httprouter.Handle
type. Use the Handler
方法 http.Handler
:
router.Handler("GET", "/", commonHandlers.ThenFunc(final))