-
Notifications
You must be signed in to change notification settings - Fork 1
/
echo.go
59 lines (52 loc) · 1.76 KB
/
echo.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
58
59
package gosimplerest
import (
"database/sql"
"net/http"
"strings"
"github.com/franciscoescher/gosimplerest/handlers"
"github.com/franciscoescher/gosimplerest/resource"
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
)
func AddEchoHandlers(r *echo.Echo, d *sql.DB, l *logrus.Logger, v *validator.Validate, resources []resource.Resource) *echo.Echo {
h := AddRouteFunctions{
Post: EchoAddRouteFunc(r.POST),
Get: EchoAddRouteFunc(r.GET),
Put: EchoAddRouteFunc(r.PUT),
Patch: EchoAddRouteFunc(r.PATCH),
Delete: EchoAddRouteFunc(r.DELETE),
Head: EchoAddRouteFunc(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
}
// EchoAddRouteType is the type of the function that echo.Echo uses to add routes to the router.
// Example: r.POST, r.GET...
type EchoAddRouteType func(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
// EchoAddRouteFunc uses the f function to add a route to the router,
// wrapping the handler to add params to request context.
func EchoAddRouteFunc(f EchoAddRouteType) AddRouteFunc {
return func(name string, h http.HandlerFunc) {
f(name, EchoHandlerWrapper(h))
}
}
// EchoHandlerWrapper converts a http.HandlerFunc to a echo.HandlerFunc
// It adds params to request context.
func EchoHandlerWrapper(h http.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
params := make(map[string]string, 0)
for _, param := range c.ParamNames() {
params[param] = c.Param(param)
}
handlers.AddParamsToHandlerFunc(h, params)(c.Response().Writer, c.Request())
return nil
}
}