1 回答
TA贡献1802条经验 获得超4个赞
处理程序中的调用不能提前终止后者。相反,您应该定义为中间件(另请参阅装饰器模式):CheckPermissionFilter
SomeHttpHandler
CheckPermissionFilter
package main
import (
"net/http"
)
func main() {
http.Handle("/foo", CheckPermissionFilter(SomeHttpHandler))
// ...
}
func CheckPermissionFilter(h http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sid, err := r.Cookie("sid")
// handle err
if !Validate(sid) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
h(w, r)
})
}
func SomeHttpHandler(w http.ResponseWriter, r *http.Request) {
// ...
}
func Validate(sid string) bool {
return true // simplistic implementation for this example
}
- 1 回答
- 0 关注
- 63 浏览
添加回答
举报