Hello World

最后更新于:2022-04-02 03:07:21

[TOC] ## 概述 ``` package main import ( "fmt" "github.com/casbin/casbin/v2" "github.com/casbin/casbin/v2/model" fileadapter "github.com/casbin/casbin/v2/persist/file-adapter" _ "github.com/go-sql-driver/mysql" "log" ) func main() { a,_:=model.NewModelFromString(` [request_definition] r = sub, obj, act [policy_definition] p = sub, obj, act [role_definition] g = _, _ [policy_effect] e = some(where (p.eft == allow)) [matchers] m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act `) b:=fileadapter.NewAdapter("D:\\workspace\\antbiz\\test\\basic_policy.csv") e, err := casbin.NewEnforcer(a,b) if err != nil { log.Fatalf("error: enforcer: %s", err) } sub := "alice" // 想要访问资源的用户。 obj := "data1" // 将被访问的资源。 act := "read" // 用户对资源执行的操作。 ok, err := e.Enforce(sub, obj, act) if err != nil { // 处理err } if ok == true { fmt.Printf("%+v\n", ok) } else { // 拒绝请求,抛出异常 fmt.Printf("%+v\n", "not allow") } roles,err := e.GetRolesForUser("alice") if err != nil { fmt.Printf("%+v\n", err) } fmt.Printf("%+v\n", roles) // 您可以使用BatchEnforce()来批量执行一些请求 // 这个方法返回布尔切片,此切片的索引对应于二维数组的行索引。 // 例如 results[0] 是 {"alice", "data1", "read"} 的结果 //results, err := e.BatchEnforce([][]interface{}{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"jack", "data3", "read"}}) } ```
';