-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
85 lines (69 loc) · 1.68 KB
/
controller.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package api
import (
"context"
"mime/multipart"
"net/http"
"strconv"
)
type Map map[string]interface{}
type StringMap map[string]string
type Request struct {
GetParams func(key string, defaultValue ...string) string
GetFile func(key string) (multipart.File, *multipart.FileHeader, error)
GetQuery func(interface{}) error
GetBody func(interface{}) error
GetHeaders func(interface{}) error
}
type Handler func(Request, context.Context) *Response
type Route struct {
Method string
Path string
Handler Handler
Version int
Middlewares *[]func(http.Handler) http.Handler
}
type RouteOption func(*Route)
func NewRoute(method string, handler Handler, opts ...RouteOption) Route {
route := Route{
Method: method,
Path: "",
Handler: handler,
Version: 1,
}
for _, opt := range opts {
opt(&route)
}
return route
}
func WithPath(path string) RouteOption {
return func(r *Route) {
r.Path = path
}
}
func WithVersion(version int) RouteOption {
return func(r *Route) {
r.Version = version
}
}
func WithMiddleware(handlers ...func(http.Handler) http.Handler) RouteOption {
return func(r *Route) {
r.Middlewares = &handlers
}
}
func (r *Route) GetVersionedPath(controllerPath string) string {
versionPrefix := "/v" + strconv.Itoa(r.Version)
return versionPrefix + controllerPath + r.Path
}
type ControllerConfig struct {
Path string
Routes []Route
Middlewares *[]func(http.Handler) http.Handler
}
type Controller interface {
GetConfig() ControllerConfig
}
type ControllerImpl struct {
}
func (ctrl *ControllerImpl) JoinMiddleware(handlers ...func(http.Handler) http.Handler) *[]func(http.Handler) http.Handler {
return &handlers
}