ACL 示例代码
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// ACL 权限表
var acl = map[string]map[string][]string{
"admin": {
"resource1": {"read", "write", "delete"},
"resource2": {"read", "write"},
},
"user": {
"resource1": {"read"},
"resource2": {"read", "write"},
},
"guest": {
"resource1": {"read"},
"resource2": {"read"},
},
}
// ACL 中间件
func ACLMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 获取用户名
username := c.Query("username")
if username == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Username is required"})
c.Abort()
return
}
// 获取请求的资源和操作
resource := c.Param("resource")
action := c.Param("action")
// 检查用户名是否存在
userPermissions, exists := acl[username]
if !exists {
c.JSON(http.StatusForbidden, gin.H{"error": "User not found or not allowed"})
c.Abort()
return
}
// 检查资源是否存在
actions, exists := userPermissions[resource]
if !exists {
c.JSON(http.Stat