如果某些权限检查失败,我如何提前终止我的处理程序?

How can I terminate my handler early if some permission check fails?

我正在寻找一种使用 http

来实现 权限检查 功能的方法

想法是有些 API 应该仅供登录会话使用。

func CheckPermissionFilter(w http.ResponseWriter, r *http.Response){
    sid, err := r.Cookie("sid")
    // check the permission with sid, if permission is granted then just let the 
    // process go on, otherwise, just break the filter chain and return Http Error Code.

}

func SomeHttpHandler(w http.ResponseWriter, r *http.Response){
     CheckPermissionFilter(w, r)
     // if not breaked by above filter function, process the request...
   
}

我的权限检查没有问题,但我找不到中断 HTTP 请求处理的方法。

在您的 SomeHttpHandler 处理程序中对 CheckPermissionFilter 的调用不能提前终止后者。相反,您应该将 CheckPermissionFilter 定义为 中间件 (另请参阅 decorator pattern):

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
}