1. Self-built HTTP middleware
1. In the form of a type
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. In the form of a function
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)
}
"description": Content from the go-web explanation, respect the original, thank the author! Go Programming Basics
beego-self-built HTTP middleware