This is a creation in Article, where the information may have evolved or changed.
Original: Golang Http handlers as middleware
Translator: YOUNGSTERXYF
Most modern Web Component stacks allow for "filtering" requests through the stack/component middleware, so that you can cleanly isolate crosscutting concerns from Web applications: Concepts in aspect-oriented programming? )。 This week I tried to implant the hooks in the Go language http.FileServer
, and I was amazed to see how easy it was to implement them.
Let's start with a basic file server:
func Main (){ http. Listenandserve (": 8080",http. Fileserver (http. Dir ("/tmp") )) }
This program will open a local file server on port 8080. So how do we implant hooks in this so that we can execute some code before the file requests processing? Look http.ListenAndServe
at the method signature:
func Listenandserve (addrstring,handlerhandler) Error
Looks like it http.FileServer
returns a Handler
---given a root directory to know how to handle a file request. Let's look at the Handler
interface:
type Handler Interface { servehttp(responsewriter, * Request)}
Depending on the interface principle of the go language, any object that ServeHTTP
is implemented is just one Handler
. So it seems that what we need to do is construct a process of our own Handler
---encapsulation http.FileServer
. The Net/http standard library module in the Go language has a helper function http.HandlerFunc
that transforms a normal function into a request handler function (handler):
type Handlerfunc func (responsewriter,*Request)
So we can encapsulate this http.FileServer
:
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)}
The Go Language net/http standard library module has many built-in processing functions, such as Timeouthandler and Redirecthandler, that can be used in the same way as mixed matches.
Translator Recommended Reading
- Golang Http Server Source Reading