Skip to content

Commit

Permalink
update handler_common & README
Browse files Browse the repository at this point in the history
  • Loading branch information
szluyu99 committed Jun 8, 2023
1 parent 942472d commit 4820900
Show file tree
Hide file tree
Showing 6 changed files with 402 additions and 70 deletions.
115 changes: 105 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,93 @@ Rabbit is a golang library for simplifying backend develop.

# Features

## Dynamic handlers
## Dynamic Handlers & Dynamic Gorm Functions

## Web Objects
```go
func HandleGet[T any](c *gin.Context, db *gorm.DB, onRender onRenderFunc[T])
func HandleDelete[T any](c *gin.Context, db *gorm.DB, onDelete onDeleteFunc[T])
func HandleCreate[T any](c *gin.Context, db *gorm.DB, onCreate onCreateFunc[T])
func HandleEdit[T any](c *gin.Context, db *gorm.DB, editables []string, onUpdate onUpdateFunc[T])
```

```go
func ExecuteGet[T any, V Key](db *gorm.DB, key V) (*T, error)
func ExecuteEdit[T any, V Key](db *gorm.DB, key V, vals map[string]any) (*T, error)
func ExecuteQuery[T any](db *gorm.DB, form QueryForm) (items []T, count int, err error)
```

About how to use: Please refer to the corresponding unit tests.

## Integration Web Objects - Generate RESTful API

Reference [https://github.com/restsend/gormpher](https://github.com/restsend/gormpher)

## Env Config

### Load environment variables

Functions:

```go
func GetEnv(key string) string
func LookupEnv(key string) (string, bool)
```

## Built-in modules
Examples:

```bash
# .env
xx
EXIST_ENV=100
```

```bash
EXIST_ENV=100 go run .
```

```go
rabbit.GetEnv("EXIST_ENV") // 100
rabbit.LookupEnv("EXIST_ENV") // 100, true
```

### Load config from DB

Functions:

```go
func CheckValue(db *gorm.DB, key, default_value string)
func SetValue(db *gorm.DB, key, value string)
func GetValue(db *gorm.DB, key string) string
func GetIntValue(db *gorm.DB, key string, default_value int) int
func GetBoolValue(db *gorm.DB, key string) bool
```

Examples:

```go
db, _ := gorm.Open(sqlite.Open("file::memory:"), nil)
db.AutoMigrate(&rabbit.Config{})

rabbit.SetValue(db, "test_key", "test_value")
value := rabbit.GetValue(db, "test_key") // test_value

rabbit.CheckValue(db, "check_key", "default_value")
value = rabbit.GetValue(db, "check_key") // default_value

rabbit.SetValue(db, "int_key", "42")
intValue := rabbit.GetIntValue(db, "int_key", -1) // 42

rabbit.SetValue(db, "bool_key", "true")
boolValue := rabbit.GetBoolValue(db, "bool_key") // true
```

## Built-in Handlers

### With authentication module

```go
RegisterAuthenticationHandlers("/auth", db, r)
```

```
GET /auth/info
Expand All @@ -22,11 +102,26 @@ POST /auth/change_password

### With authorization module

```go
rabbit.RegisterAuthorizationHandlers(db, r.Group("/api"))
```

```
PUT /api/role
PATCH /api/role/:key
DELETE /api/role/:key
PUT /api/permission
PATCH /api/permission/:key
DELETE /api/permission/:key
```

### With middleware module

```go
ar := r.Group("/api").Use(
rabbit.WithAuthentication(),
rabbit.WithAuthorization("/api"),
)

rabbit.RegisterAuthorizationHandlers(db, ar)
```
PUT /auth/role
PATCH /auth/role/:key
DELETE /auth/role/:key
PUT /auth/permission
PATCH /auth/permission/:key
DELETE /auth/permission/:key
```
2 changes: 1 addition & 1 deletion auths.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ func GetPermissionByName(db *gorm.DB, name string) (*Permission, error) {
}

func GetPermission(db *gorm.DB, uri, method string) (*Permission, error) {
return Get(db.Debug(), &Permission{Uri: uri, Method: method})
return Get(db, &Permission{Uri: uri, Method: method})
}

func GetPermissionsByRole(db *gorm.DB, rid uint) ([]*Permission, error) {
Expand Down
27 changes: 22 additions & 5 deletions configs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,40 @@ import (
)

func TestEnv(t *testing.T) {
// not exist .env file
v := GetEnv("NOT_EXIST_ENV")
assert.Empty(t, v)
defer os.Remove(".env")

// write .env file
os.WriteFile(".env", []byte(`
#hello
xx
EXIST_ENV = 100
EXIST_ENV=100
`), 0666)

v = GetEnv("EXIST_ENV")
assert.Equal(t, v, "100")
{
v = GetEnv("EXIST_ENV")
assert.Equal(t, v, "100")

v = GetEnv("NOT_EXIST_ENV")
assert.Empty(t, v)
}

{
v, ok := LookupEnv("EXIST_ENV")
assert.Equal(t, v, "100")
assert.True(t, ok)

v, ok = LookupEnv("NOT_EXIST_ENV")
assert.Empty(t, v)
assert.False(t, ok)
}

}

func TestConfigFunctions(t *testing.T) {
// 初始化数据库
db, _ := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
db, _ := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{})
db.AutoMigrate(&Config{})

// Test SetValue and GetValue
Expand Down
18 changes: 15 additions & 3 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ func main() {
}
}

// logger with color
rabbit.EnabledConsoleColor = true
rabbit.Infoln("Server started", "addr", serverAddr)

// TEST_KEY=100 go run main.go
key := rabbit.GetEnv("TEST_KEY")
if key != "" {
rabbit.Infoln("TEST_KEY", key)
} else {
rabbit.Errorln("TEST_KEY not found")
}

// db
db := rabbit.InitDatabase(dbDriver, dsn, lw)

Expand All @@ -45,9 +57,9 @@ func main() {
// init rabbit
rabbit.InitRabbit(db, r)

// logger with color
rabbit.EnabledConsoleColor = true
rabbit.Infoln("Server started", "addr", serverAddr)
// register handlers
ar := r.Group("/api").Use(rabbit.WithAuthentication(), rabbit.WithAuthorization("/api"))
rabbit.RegisterAuthorizationHandlers(db, ar)

r.Run(serverAddr)
}
Loading

0 comments on commit 4820900

Please sign in to comment.