-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint.go
86 lines (70 loc) · 1.62 KB
/
endpoint.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
86
package go_raft
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type Option interface {
apply(e *Endpoint)
}
type optionFunc func(e *Endpoint)
func (f optionFunc) apply(e *Endpoint) {
f(e)
}
func WithEndpointName(name string) Option {
return optionFunc(func(e *Endpoint) {
e.name = name
})
}
func WithEndpointPath(path string) Option {
return optionFunc(func(e *Endpoint) {
e.relativePath = path
})
}
func WithEndpointGet(handler gin.HandlerFunc) Option {
return optionFunc(func(e *Endpoint) {
e.handlers[http.MethodGet] = handler
})
}
func WithEndpointPost(handler gin.HandlerFunc) Option {
return optionFunc(func(e *Endpoint) {
e.handlers[http.MethodPost] = handler
})
}
func WithEndpointDelete(handler gin.HandlerFunc) Option {
return optionFunc(func(e *Endpoint) {
e.handlers[http.MethodDelete] = handler
})
}
func WithEndpointPut(handler gin.HandlerFunc) Option {
return optionFunc(func(e *Endpoint) {
e.handlers[http.MethodPut] = handler
})
}
func WithEndpointPatch(handler gin.HandlerFunc) Option {
return optionFunc(func(e *Endpoint) {
e.handlers[http.MethodPatch] = handler
})
}
type Endpoint struct {
// should be unique
name string
relativePath string
handlers map[string]gin.HandlerFunc
}
func NewEndpoint(opts ...Option) Endpoint {
ept := Endpoint{
handlers: make(map[string]gin.HandlerFunc),
}
for _, opt := range opts {
opt.apply(&ept)
}
return ept
}
func Register(endpoint Endpoint) error {
if _, exist := endpoints[endpoint.name]; exist {
return fmt.Errorf("endpoint [%s] already exist", endpoint.name)
}
endpoints[endpoint.name] = endpoint
return nil
}