-
Notifications
You must be signed in to change notification settings - Fork 1
/
gin.go
57 lines (51 loc) · 1.7 KB
/
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
51
52
53
54
55
56
57
package gosimplerest
import (
"database/sql"
"net/http"
"strings"
"github.com/franciscoescher/gosimplerest/handlers"
"github.com/franciscoescher/gosimplerest/resource"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/sirupsen/logrus"
)
func AddGinHandlers(r *gin.Engine, d *sql.DB, l *logrus.Logger, v *validator.Validate, resources []resource.Resource) *gin.Engine {
h := AddRouteFunctions{
Post: GinAddRouteFunc(r.POST),
Get: GinAddRouteFunc(r.GET),
Put: GinAddRouteFunc(r.PUT),
Patch: GinAddRouteFunc(r.PATCH),
Delete: GinAddRouteFunc(r.DELETE),
Head: GinAddRouteFunc(r.HEAD),
}
apf := func(name string, param string) string {
var sb strings.Builder
sb.WriteString(name)
sb.WriteString("/:")
sb.WriteString(param)
return sb.String()
}
AddHandlers(d, l, v, h, apf, resources)
return r
}
// GinAddRouteType is the type of the function that gin.Engine uses to add routes to the router.
// Example: r.POST, r.GET...
type GinAddRouteType func(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes
// GinAddRouteFunc uses the f function to add a route to the router,
// wrapping the handler to add params to request context.
func GinAddRouteFunc(f GinAddRouteType) AddRouteFunc {
return func(name string, h http.HandlerFunc) {
f(name, GinHandlerWrapper(h))
}
}
// GinHandlerWrapper converts a http.HandlerFunc to a gin.HandlerFunc
// It adds params to request context.
func GinHandlerWrapper(h http.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
params := make(map[string]string, 0)
for _, param := range c.Params {
params[param.Key] = param.Value
}
handlers.AddParamsToHandlerFunc(h, params)(c.Writer, c.Request)
}
}