diff --git a/README.md b/README.md index ff2b04f..005a02c 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,46 @@ func main() { e.SavePolicy() } ``` + +## Simple PostgreSQL Example + +```go +package main + +import ( + "github.com/casbin/casbin/v2" + gormadapter "github.com/casbin/gorm-adapter/v3" + _ "github.com/lib/pq" +) + +func main() { + // Initialize a Gorm adapter and use it in a Casbin enforcer: + // The adapter will use the PostgreSQL database named "casbin". + // If it doesn't exist, the adapter will create it automatically. + // You can also use an already existing gorm instance with gormadapter.NewAdapterByDB(gormInstance) + a, _ := gormadapter.NewAdapter("postgres", "host=127.0.0.1 port=5432 user=postgres password=postgres sslmode=disable") // Your driver and data source. + e, _ := casbin.NewEnforcer("examples/rbac_model.conf", a) + + // Or you can use an existing DB "abc" like this: + // The adapter will use the table named "casbin_rule". + // If it doesn't exist, the adapter will create it automatically. + // a := gormadapter.NewAdapter("postgres", "host=127.0.0.1 port=5432 user=postgres password=postgres dbname=abc sslmode=disable", true) + + // Load the policy from DB. + e.LoadPolicy() + + // Check the permission. + e.Enforce("alice", "data1", "read") + + // Modify the policy. + // e.AddPolicy(...) + // e.RemovePolicy(...) + + // Save the policy back to DB. + e.SavePolicy() +} +``` + ## Turn off AutoMigrate New an adapter will use ``AutoMigrate`` by default for create table, if you want to turn it off, please use API ``TurnOffAutoMigrate(db *gorm.DB) *gorm.DB``. See example: ```go