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 + Casbin 权限控制实战

以上是关于Iris——整合Gorm持久化的Casbin的Example的主要内容,如果未能解决你的问题,请参考以下文章

Casbin-forum锛氫竴娆?React + Golang 鐨勯珮浠?V2EX 璁哄潧椤圭洰

检索域的 GORM 持久属性列表

如何使用 GORM 测试实例是不是持久化到数据库中?

GORM数据服务VS Grails服务

[开源]如何使用goapp写你的后台管理系统_golang

Iris——整合go-playground/validator参数校验Demo