这篇文章给大家介绍Golang中怎么自建一个HTTP中间件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
自建Http中间件
* 以类型形式
* 以函数形式
* 追加响应内容
* 自定义响应
以类型形式:
package main
import (
"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)
}
以函数形式:
package main
import (
"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)
}
自定义响应: net/http/httptest:响应请求时先进记录,不直接响应客户端,在完全自定义时,还没准备好响应给客户端,先将请求虚拟记录下来,没有真正的相应出去,都在一个记录过程当中,在完全处理完后,在将响应一整套的响应给客户。
package main
//追加响应,传入handler 提示经过中间件处理
import (
"net/http"
)
type AppendHiddleware struct{
handler http.Handler
}
func (this *AppendHiddleware)ServeHTTP(w http.ResponseWriter,r *http.Request){
if r.Host=="ccc"{
this.handler.ServeHTTP(w,r)
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)
}
关于Golang中怎么自建一个HTTP中间件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4209186/blog/3120822