orce(string(username), obj, act, enforcer)
if err != nil {
log.Println(err)
c.AbortWithStatusJSON(500, component.RestResponse{Message: "error occurred when authorizing user"})
return
}
if !ok {
c.AbortWithStatusJSON(403, component.RestResponse{Message: "forbidden"})
return
}
c.Next()
}
}
reader.go 读取yaml配置文件的根据类,使用了viter
package config
import (
"fmt"
"github.com/spf13/viper"
"log"
"sync"
"time"
)
type Config struct {
Server *Server
Mysql *DB
LocalCache *LocalCache
Casbin *Casbin
}
type Server struct {
Port int64
}
type DB struct {
Username string
Password string
Host string
Port int64
Dbname string
TimeOut string
}
type LocalCache struct {
ExpireTime time.Duration
}
type Casbin struct {
Model string
}
var (
once sync.Once
Reader = new(Config)
)
func (config *Config) ReadConfig() *Config {
once.Do(func() {
viper.SetConfigName("config") // filename
viper.SetConfigType("yaml") // filename extension : yaml | json |
viper.AddConfigPath("./config") // workspace dir : ./
var err error
err = viper.ReadInConfig() // read config
if err != nil { // handler err
log.Fatalf(fmt.Sprintf("Fatal error config file: %s \n", err))
}
err = viper.Unmarshal(config)
if err != nil {
log.Fatalf(fmt.Sprintf("Fatal error viper unmarshal config: %s \n", err))
}
})
return Reader
}
配置文件
server:
port: 8080
mysql:
username: root
password: pwd
host: 127.0.0.1
port: 3306
dbname: casbin_demo
timeout: 10s
localCache:
expireTime: 60
casbin:
model: config/rbac_model.conf
persistence.go, gorm,bigcache, casbin 初始化,这里用的casbin是从数据库读取policy
package component
import (
"fmt"
"github.com/allegro/bigcache"
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
_ "github.com/go-sql-driver/mysql"
"go-web-demo/config"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
"time"
)
var (
DB *gorm.DB
GlobalCache *bigcache.BigCache
Enforcer *casbin.Enforcer
)
// CreateByConfig create components
func CreateByConfig() {
ConnectDB()
CreateLocalCache()
CreateCasbinEnforcer()
}
func ConnectDB() {
// connect to DB
var err error
dbConfig := config.Reader.ReadConfig().Mysql
if dbConfig == nil {
log.Fatalf(fmt.Sprintf("db config is nil"))
}
// config
username := dbConfig.Username
password := dbConfig.Password
host := dbConfig.Host
port := dbConfig.Port
Dbname := dbConfig.Dbname
timeout := dbConfig.TimeOut
dbUrl := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s", username, password, host, port, Dbname, timeout)
log.Println("connect db url: " + dbUrl)
DB, err = gorm.Open(mysql.Open(dbUrl), &gorm.Config{})
if err != nil {
log.Fatalf(fmt.Sprintf("failed to connect to DB: %v", err))
}
}
func CreateLocalCache() {
var err error
cacheConfig := config.Reader.ReadConfig().LocalCache
if cacheConfig == nil {
log.Fatalf(fmt.Sprintf("cache config is nil&q