假设我想在运行针对HTTP服务器的自定义多路复用器之前先运行记录器。
在那儿,我可以链接记录器并添加这样的自定义多路复用器:https : //play.golang.org/p/Edurl-Rhqb9
package main
import (
"fmt"
"net/http"
"time"
"github.com/julienschmidt/httprouter"
)
type Middleware func(http.HandlerFunc) http.HandlerFunc
func ServeHTTPIterator(h http.HandlerFunc, m ...Middleware) http.HandlerFunc {
if len(m) < 1 {
return h
}
wrapped := h
// loop in reverse to preserve middleware order
for i := len(m) - 1; i >= 0; i-- {
wrapped = m[i](wrapped)
}
return wrapped
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Index!")
}
func LogFirst(h http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Print(`First`)
h.ServeHTTP(w, r)
})
}
func LogSecond(h http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Print(`Second`)
h.ServeHTTP(w, r)
})
}
func main() {
httpServer := &http.Server{
Addr: `my.local:8080`,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 5 * time.Second,
}
var Router *httprouter.Router
preMiddle := []Middleware{
LogFirst,
LogSecond,
}
http.HandleFunc("/", ServeHTTPIterator(IndexHandler, preMiddle...))
httpServer.Handler = Router
}
但是现在假设我想在记录器之后运行多路复用器,在那种情况下,我想我会做类似的事情:
preMiddle := []Middleware{
LogFirst,
LogSecond,
Router,
}
但是我不确定如何包装Router来完成这项工作,或者这是否合法。有人可以告诉我我在这里缺少什么吗?
修改代码以使用http.Handler而不是http.HandlerFunc。
type Middleware func(http.Handler) http.Handler
func ServeHTTPIterator(h http.Handler, m ...Middleware) http.Handler {
if len(m) < 1 {
return h
}
wrapped := h
// loop in reverse to preserve middleware order
for i := len(m) - 1; i >= 0; i-- {
wrapped = m[i](wrapped)
}
return wrapped
}
func LogFirst(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Print(`First`)
h.ServeHTTP(w, r)
})
}
func LogSecond(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Print(`Second`)
h.ServeHTTP(w, r)
})
}
创建路由器并向路由器注册处理程序。将参数参数添加到IndexHandler,以便该功能与httprouter兼容。
router := httprouter.New()
router.GET("/", IndexHandler)
使用新版本的ServeHTTPIterator包装路由器。
httpServer.Handler = ServeHTTPIterator(router, preMiddle...)
通过这些更改,将在调用路由器之前写入日志。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句