标签:fun block 内容 server bsp serve writer head com
1.以类型的形式
type SingleHost struct{
handler http.Handler
allowedHost string
}
func (this *SingleHost)ServerHTTP(w http.ResponseWriter,r *http.Request){
if r.host == this.allowedHost {
this.handler.ServerHTTP(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 : ”localhost:8080”
}
http.ListenAndServe(“:8080”,single)
}
2. 以函数的形式
func SingleHost (handler http.Handler,allowHost string){
fn:= func(w http.ResponseWriter,r *http.Request){
if r.host == allowedHost {
handler.ServerHTTP(w,r)
} else{
w.WriteHeader(403)
}
}
return http.HandlerFunc(fn)
}
【说明】: 内容来自无闻的go-web讲解,尊重原版,感谢作者! Go编程基础
标签:fun block 内容 server bsp serve writer head com
原文地址:https://www.cnblogs.com/tomtellyou/p/9575656.html