Golang Http Handlers as Middleware

songbohr · · 1633 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
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

入群交流(和以上内容无关):加入Go大咖交流群,免费领全套学习资料或添加微信:muxilin131420 备注:入群;或加QQ群:729884609

1633 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传