Iris——整合Gorm持久化的Casbin的Example
Posted Starzkg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Iris——整合Gorm持久化的Casbin的Example相关的知识,希望对你有一定的参考价值。
源代码:https://gitee.com/shentuzhigang/mini-project/tree/master/iris_demo/casbin_demo
Go Module
go get github.com/kataras/iris/v12
go get github.com/casbin/casbin/v2
go get gorm.io/gorm
go get gorm.io/driver/mysql
go get github.com/casbin/gorm-adapter/v3
Example
package main
import (
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
casbinMiddleware "github.com/iris-contrib/middleware/casbin"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/basicauth"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func hi(ctx iris.Context) {
ctx.Writef("Hello %s", casbinMiddleware.Subject(ctx))
}
func newApp() *iris.Application {
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "root:123456@tcp(127.0.0.1:3306)/test",
DontSupportRenameColumn: false,
DontSupportRenameIndex: false,
DisableDatetimePrecision: false,
DefaultStringSize: 256,
}), &gorm.Config{SkipDefaultTransaction: true})
if err != nil {
return nil
}
var a, _ = gormadapter.NewAdapterByDB(db)
var Enforcer, _ = casbin.NewEnforcer("casbinmodel.conf", a)
middleware := casbinMiddleware.New(Enforcer)
app := iris.New()
app.Logger().SetLevel("debug")
app.Use(basicauth.Default(map[string]string{
"bob": "bobpass",
"alice": "alicepass",
}))
app.Use(middleware.ServeHTTP)
app.Get("/", hi)
app.Get("/dataset1/{p:path}", hi) // p, alice, /dataset1/*, GET
app.Post("/dataset1/resource1", hi)
app.Get("/dataset2/resource2", hi)
app.Post("/dataset2/folder1/{p:path}", hi)
app.Any("/dataset2/resource1", hi)
return app
}
func main() {
app := newApp()
app.Listen(":8080")
}
参考文章
以上是关于Iris——整合Gorm持久化的Casbin的Example的主要内容,如果未能解决你的问题,请参考以下文章