如果某个权限检查失败,你想要提前终止处理程序,你可以使用以下方法:

huangapple go评论82阅读模式
英文:

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")
    // 使用sid检查权限,如果权限被授予,则继续处理,否则中断过滤器链并返回HTTP错误代码。

}

func SomeHttpHandler(w http.ResponseWriter, r *http.Response){
     CheckPermissionFilter(w, r)
     // 如果上述过滤器函数没有中断,继续处理请求...
   
}

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

英文:

I am finding a way to implement the permission check functionality using http

The idea is there are APIs that should be used only by login sessions.

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...
   
}

I have no problem with the permission checking, but I can't find a way to break the HTTP Request processing.

答案1

得分: 2

在你的SomeHttpHandler处理程序中,对CheckPermissionFilter的调用不能提前终止后者的执行。相反,你应该将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")
		// 处理错误
		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 // 这个例子中的简单实现
}

希望对你有帮助!

英文:

The call to CheckPermissionFilter within your SomeHttpHandler handler cannot terminate the latter early. Instead, you should define CheckPermissionFilter as a middleware (see also 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
}

huangapple
  • 本文由 发表于 2021年9月4日 15:08:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/69053135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定