package main //中间件1:只允许特定host请求过来 import ( "fmt" "net/http" ) //SingleHost是一个中间件, type SingleHost struct { hander http.Handler //这不是继承http.Handler接口,后面重写了ServeHTTP方法。 /* type Handler interface { ServeHTTP(ResponseWriter, *Request) }*/ allowedHost string //只准允许某个host发来的请求 } //Handler这个接口只有一个方法,SingleHost实现了这个方法就相当于继承了Handler interface接口 //请求来的时候会来这里 func (this *SingleHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Println(r.Host) if r.Host == this.allowedHost { //从Request里面可以获取Host this.hander.ServeHTTP(w, r) } else { w.WriteHeader(403) } } func myHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("helloworld")) } func main() { sing := &SingleHost{ hander: http.HandlerFunc(myHandler), allowedHost: "example.com", //只有example.com过来的才合法 } http.ListenAndServe(":8080", sing) }
中间件形式2:函数形式
package main //中间件2:只允许特定host请求过来。 //函数的形式。 import ( "fmt" "net/http" ) /* type HandlerFunc func(ResponseWriter, *Request) // ServeHTTP calls f(w, r). func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) } */ func SingleHost(handler http.Handler, allowstring string) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { if r.Host == allowstring { //从Request里面可以获取Host this.hander.ServeHTTP(w, r) } else { w.WriteHeader(403) } } return http.HandlerFunc(fn) } func myHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("helloworld")) } func main() { sing := SingleHost(http.HandlerFunc(myHandler), "example.com") http.ListenAndServe(":8080", sing) }
package main //中间件3:只允许特定host请求过来。 //追加内容形式。 import ( _ "fmt" "net/http" ) type AppendMiddleware struct { handler http.Handler } func (this *AppendMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { this.handler.ServeHTTP(w, r) //正常是响应 w.Write([]byte("Hey,this is middleware")) //多输出一行内容,告诉用户这是中间价 } func myHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("helloworld")) } func main() { mid := &AppendMiddleware{http.HandlerFunc(myHandler)} http.ListenAndServe(":8080", mid) }
package main //中间件3:只允许特定host请求过来。 //自定义响应。 import ( _ "fmt" "net/http" "net/http/httpest" ) //先将所有的响应保存起来,完成所有操作之后,然后一起输出 type ModifiedMiddleware struct { handler http.Handler } func (this *ModifiedMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { rec := httptest.NewRecorder() this.handler.ServeHTTP(rec, r) //rec将所有的响应记录下来 for k, v := range rec.Header() { w.Header()[k] = v } w.Header().Set("go-web-foundation", "vip") w.WriteHeader(418) w.Write([]byte("this is middleware")) w.Write(rec.Body.Bytes()) } func myHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("helloworld")) } func main() { mid := &ModifiedMiddleware{http.HandlerFunc(myHandler)} http.ListenAndServe(":8080", mid) }