Golang Http Handlers as Middleware

From: http://capotej.com/

转者按:本文介绍了如何hook一个http的处理函数,从而加入自定义的内容。


Most modern web stacks allow the “filtering” of requests via stackable/composable middleware, allowing you to cleanly separate cross-cutting concerns from your web application. This weekend I needed to hook into go’shttp.FileServer and was pleasantly surprised how easy it was to do.

Let’s start with a basic file server for /tmp:

main.go
1
2
3
func main() {
    http.ListenAndServe(":8080", http.FileServer(http.Dir("/tmp")))
}

This starts up a local file server at :8080. How can we hook into this so we can run some code before file requests are served? Let’s look at the method signature for http.ListenAndServe:

1
func ListenAndServe(addr string, handler Handler) error

So it looks like http.FileServer returns a Handler that knows how to serve files given a root directory. Now let’s look at the Handler interface:

1
2
3
type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

Because of go’s granular interfaces, any object can be a Handler so long as it implements ServeHTTP. It seems all we need to do is construct our own Handler that wraps http.FileServer’s handler. There’s a built in helper for turning ordinary functions into handlers called http.HandlerFunc:

1
type HandlerFunc func(ResponseWriter, *Request)

Then we just wrap http.FileServer like so:

main.go
1
2
3
4
5
6
7
8
9
10
11
12
func OurLoggingHandler(h http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    fmt.Println(*r.URL)
    h.ServeHTTP(w, r)
  })
}

func main() {
    fileHandler := http.FileServer(http.Dir("/tmp"))
    wrappedHandler := OurLoggingHandler(fileHandler)
    http.ListenAndServe(":8080", wrappedHandler)
}

Go has a bunch of other builtin handlers like TimeoutHandler and RedirectHandler that can be mixed and matched the same way.


另一种方式参考https://github.com/philsong/golang_samples/blob/master/src/emvdecoder/emvdecoder.go


type TraceHandler struct {
        h http.Handler
        n int
}

func (r *TraceHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
        r.n++
        fmt.Printf("counter = %d\n", r.n) //why counter always zero
        fmt.Println("get", req.URL.Path, " from ", req.RemoteAddr)
        r.h.ServeHTTP(w, req)
}

func main() {
        port := "9090" //Default port
        if len(os.Args) > 1 {
                port = strings.Join(os.Args[1:2], "")
        }
        h := http.StripPrefix("/icclogs/", http.FileServer(http.Dir("./logs/")))
        http.Handle("/icclogs/", &TraceHandler{h: h, n: 0})

        println("Listening on port ", port, "...")
        err := http.ListenAndServe(":"+port, nil) //设置监听的端口

        if err != nil {
                log.Fatal("ListenAndServe: ", err)
        }
}


本文来自:CSDN博客

感谢作者:songbohr

查看原文:Golang Http Handlers as Middleware

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。