有几个选项。第一个是返回一个 error 响应:
func handle(w http.ResponseWriter,r *http.Request) {
if r.UserAgent() == "test/1.0" {
//Allow
} else {
http.Error(w,"forbidden",http.StatusForbidden)
return
}
}
第二种是hijack与服务器的连接并粗暴地关闭连接:
func handle(w http.ResponseWriter,r *http.Request) {
if r.UserAgent() == "test/1.0" {
//Allow
} else {
if h,ok := w.(http.Hijacker); ok {
c,_,err := h.Hijack()
if err != nil {
c.Close()
return
}
}
// fallback to error response
http.Error(w,http.StatusForbidden)
return
}
}