forked from worldOneo/crudist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crudist_gin.go
50 lines (40 loc) · 1.09 KB
/
crudist_gin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package crudist
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// GinOperator type for Crudists gin implementation
type GinOperator struct {
server *gin.Engine
db *gorm.DB
}
func (g *GinOperator) DB() *gorm.DB {
return g.db
}
func (g *GinOperator) Get(path string, handler ...HandlerFunc) {
g.server.GET(path, g.toGinHandler(handler...)...)
}
func (g *GinOperator) Post(path string, handler ...HandlerFunc) {
g.server.POST(path, g.toGinHandler(handler...)...)
}
func (g *GinOperator) Patch(path string, handler ...HandlerFunc) {
g.server.PATCH(path, g.toGinHandler(handler...)...)
}
func (g *GinOperator) Delete(path string, handler ...HandlerFunc) {
g.server.DELETE(path, g.toGinHandler(handler...)...)
}
func (g *GinOperator) toContext(ctx *gin.Context) Context {
return NewGinContext(ctx)
}
func (g *GinOperator) toGinHandler(handlers ...HandlerFunc) []gin.HandlerFunc {
new := make([]gin.HandlerFunc, len(handlers))
for i, handler := range handlers {
new[i] = func(ctx *gin.Context) {
err := handler(g.toContext(ctx))
if err != nil {
ctx.Error(err)
}
}
}
return new
}