How to build a HTTP Middleware in Golang
This article introduces how to build a HTTP middleware in Golang, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Self-built Http middleware
* in the form of type * in the form of function * append response content * Custom response
In the form of type
Package mainimport ("net/http") type SingleHost struct {handler http.Handler allowedHost string} func (this * SingleHost) ServeHTTP (w http.ResponseWriter, r * http.Request) {if r.Host = = this.allowedHost {this.handler.ServeHTTP (w, r)} else {w.WriteHeader (403)} func myHandler (w http.ResponseWriter R * http.Request) {w.Write ([] byte ("hello world!"))} func main () {single: = & SingleHost {handler: http.HandlerFunc (myHandler), allowedHost: "baidu.com",} http.ListenAndServe (": 8080", single)}
In functional form:
Package mainimport ("net/http") func SingleHost (handler http.Handler, allowedHost string) http.Handler {fn: = func (w http.ResponseWriter, r * http.Request) {if r.Host = = r.allowedHost {handler.ServeHTTP (w) R)} else {w.WriteHeader (403)}} return http.HandlerFunc (fn)} func myHandler (w http.ResponseWriter,r * http.Request) {w.Write ([] byte ("hello world!"))} func main () {single:=SingleHost (http.HandlerFunc (myHandler), "localhost:8080") http.ListenAndServe (": 8080" Single)}
Custom response: net/http/httptest: advanced record when responding to the request, not directly responding to the client. When the request is completely customized, it is not ready to respond to the client. First, the request is virtually recorded, and there is no real corresponding out. It is all in a recording process. After the complete processing, a complete set of responses are given to the customer.
Package main// append response The incoming handler prompt is processed by middleware import ("net/http") type AppendHiddleware struct {handler http.Handler} func (this * AppendHiddleware) ServeHTTP (w http.ResponseWriter,r * http.Request) {if r.Hostworthy = "ccc" {this.handler.ServeHTTP (wmirr) w.Write ([] byte ("Hey) This is middleware ")} else {w.Write ([] byte (" no host "))}} func myHandle (w http.ResponseWriter,r * http.Request) {w.Write ([] byte (" hello myHandle! "))} func main () {mid:=&AppendHiddleware {http.HandlerFunc (myHandle)} http.ListenAndServe (": 8080 ") Mid)} this is about how to build a HTTP middleware in Golang. I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.