登录
首页 >  Golang >  Go问答

如何在权限检查失败时及时终止处理程序流程?

来源:stackoverflow

时间:2024-03-10 16:21:22 438浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《如何在权限检查失败时及时终止处理程序流程?》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在寻找一种使用 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
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>