-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
128 lines (113 loc) · 2.51 KB
/
api.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package api
import (
"encoding/json"
"net/http"
apiErr "github.com/94peter/sterna/api/err"
"github.com/94peter/sterna/api/mid"
"github.com/94peter/sterna/auth"
"github.com/gorilla/mux"
)
func OutputJson(w http.ResponseWriter, statusCode int, data interface{}) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(statusCode)
err := json.NewEncoder(w).Encode(data)
if err != nil {
apiErr.OutputErr(w, err)
}
}
type APIHandler struct {
Path string
Next func(http.ResponseWriter, *http.Request)
Method string
Auth bool
Group []auth.UserPerm
}
type API interface {
GetAPIs() []*APIHandler
GetName() string
}
type ApiDI interface {
InitAPI(
r *mux.Router,
middles []mid.Middle,
authMiddle mid.AuthMidInter,
apis ...API,
)
GetPort() string
EnableCORS() bool
}
func NewApiConf(port string, cors bool, ignoreMids []string, ignoreApis []string) *APIConf {
conf := &APIConf{
Port: port,
Cors: cors,
}
if len(ignoreMids) > 0 {
conf.Middle = make(map[string]bool)
}
for _, k := range ignoreMids {
conf.Middle[k] = false
}
if len(ignoreApis) > 0 {
conf.Apis = make(map[string]bool)
}
for _, k := range ignoreApis {
conf.Apis[k] = false
}
return conf
}
type APIConf struct {
Port string `yaml:"port,omitempty"`
Cors bool `yaml:"cors"`
Middle map[string]bool `yaml:"middle,omitempty"`
Apis map[string]bool `yaml:"api,omitempty"`
}
func (ac *APIConf) apiEnable(name string) bool {
if v, ok := ac.Apis[name]; ok {
return v
}
return true
}
func (ac *APIConf) middleEnable(name string) bool {
if v, ok := ac.Middle[name]; ok {
return v
}
return true
}
func (ac *APIConf) getMiddleList(ml []mid.Middle) []mid.Middleware {
var middlewares []mid.Middleware
for _, m := range ml {
if !ac.middleEnable(m.GetName()) {
continue
}
middlewares = append(middlewares, m.GetMiddleWare())
}
return middlewares
}
func (ac *APIConf) EnableCORS() bool {
return ac.Cors
}
func (ac *APIConf) GetPort() string {
return ac.Port
}
func (ac *APIConf) InitAPI(
r *mux.Router,
middles []mid.Middle,
authMiddle mid.AuthMidInter,
apis ...API,
) {
if ac == nil {
panic("api not set")
}
ml := ac.getMiddleList(middles)
for _, myapi := range apis {
if !ac.apiEnable(myapi.GetName()) {
continue
}
for _, handler := range myapi.GetAPIs() {
if authMiddle != nil {
authMiddle.AddAuthPath(handler.Path, handler.Method, handler.Auth, handler.Group)
}
r.HandleFunc(handler.Path, mid.BuildChain(handler.Next, ml...)).Methods(handler.Method)
}
}
}