-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdraft.go
More file actions
297 lines (249 loc) · 6.08 KB
/
draft.go
File metadata and controls
297 lines (249 loc) · 6.08 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package draft
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
// APIService -
type APIService struct {
http.Handler
mux *http.ServeMux
config Config
routes map[string]apiServiceRoute
rootGroup *apiGroupEntry
activeGroup *apiGroupEntry
endpointClient *http.Client
}
type apiServiceRoute struct {
handler http.Handler
ctrl EndpointAPI
}
type apiGroupEntry struct {
Type string `json:"type"`
Name string `json:"name"`
Description string `json:"description"`
Scheme *JSONScheme `json:"scheme"`
Entries []*apiGroupEntry `json:"entries"`
}
func (api *APIService) getGodraftScheme() *apiGroupEntry {
if len(api.rootGroup.Entries) == 0 {
for p := range api.routes {
api.rootGroup.Entries = append(api.rootGroup.Entries, createGroupEntry("E", p, ""))
}
}
return api.rootGroup.init(api)
}
// GroupHandler -
type GroupHandler interface {
http.Handler
Routes() []string
}
// Group -
type Group struct {
name string
items []EndpointAPI
}
// Compose -
func Compose(name string, items ...EndpointAPI) Group {
return Group{name, items}
}
// Add -
func (api *APIService) Add(g Group, groupHandlers ...GroupHandler) {
api.Group(g.name, "", func() {
for _, item := range g.items {
item.InitEndpoint(item)
api.Handle(
item,
findGroupHandler(item.URL(), groupHandlers, item.GetHandler()),
)
}
})
}
// ListenAndServe -
func (api *APIService) ListenAndServe(addr string) error {
return http.ListenAndServe(addr, api)
}
// ServeHTTP -
func (api *APIService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if api.config.DevMode {
if strings.Contains(path, "/godraft:request/") {
doDraftRequest(api, w, r)
return
}
if strings.Contains(path, "/godraft:doc") {
RenderDOC(api, w, r)
return
}
if path == "/godraft:scheme/" {
result, err := json.Marshal(api.getGodraftScheme())
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err != nil {
w.Header().Set("X-GODraft-Scheme-Marshal-Error", err.Error())
w.Write([]byte(fmt.Sprintf(`{"error":%q}`, err.Error())))
return
}
w.Write(result)
return
}
path = strings.Replace(path, "/godraft/", "/", 1)
path = strings.Replace(path, "/godraft:scheme/", "/", 1)
}
route, exists := api.routes[path]
if exists {
if path != r.URL.Path || !isHTTPHandler(route.handler) {
if api.config.DevMode {
route.ctrl.ServeHTTP(w, r)
return
}
} else {
route.handler.ServeHTTP(w, r)
return
}
}
w.WriteHeader(404)
_, _ = w.Write([]byte(fmt.Sprintf("'%s' not found", path)))
}
// URLs -
func (api *APIService) URLs() []string {
list := make([]string, 0, len(api.routes))
for u := range api.routes {
list = append(list, u)
}
return list
}
func createGroupEntry(t, name, description string) *apiGroupEntry {
return &apiGroupEntry{
Type: t,
Name: name,
Description: description,
Entries: make([]*apiGroupEntry, 0),
}
}
// Group -
func (api *APIService) Group(name, description string, executer func()) {
parent := api.activeGroup
api.activeGroup = createGroupEntry("G", name, description)
parent.Entries = append(parent.Entries, api.activeGroup)
executer()
api.activeGroup = parent
}
// GroupHR -
func (api *APIService) GroupHR() {
api.activeGroup.Entries = append(api.activeGroup.Entries, createGroupEntry("HR", "", ""))
}
// Handle -
func (api *APIService) Handle(endpoint EndpointAPI, handler http.Handler) {
endpoint.InitEndpoint(endpoint)
pattern := endpoint.URL()
api.activeGroup.Entries = append(api.activeGroup.Entries, createGroupEntry("E", pattern, ""))
api.routes[pattern] = apiServiceRoute{
handler: handler,
ctrl: endpoint,
}
if api.config.MockMode == MockEnable {
if isHTTPHandler(handler) {
api.mux.Handle(pattern, handler)
} else if api.config.DevMode {
api.mux.Handle(pattern, api)
}
}
if api.config.DevMode {
api.mux.Handle("/godraft"+pattern, api)
api.mux.Handle("/godraft:doc"+pattern, api)
api.mux.Handle("/godraft:docs"+pattern, api)
api.mux.Handle("/godraft:scheme"+pattern, api)
}
}
// ugly!
var draftHandled = false
// Config -
type Config struct {
DevMode bool
ClientConfig ClientConfig
MockMode MockMode
}
// ClientConfig -
type ClientConfig struct {
RequestTimeout time.Duration
SkipVerifyCert bool
}
// MockMode -
type MockMode int
const (
MockEnable MockMode = iota
MockDisable
)
// Create -
func Create(cfg Config) *APIService {
return CreateWithMux(http.DefaultServeMux, cfg)
}
func CreateWithMux(mux *http.ServeMux, cfg Config) *APIService {
if mux == nil {
mux = http.DefaultServeMux
}
root := createGroupEntry("G", "#root", "")
srv := &APIService{
mux: mux,
config: cfg,
rootGroup: root,
activeGroup: root,
routes: make(map[string]apiServiceRoute),
endpointClient: &http.Client{
Timeout: cfg.ClientConfig.RequestTimeout,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: cfg.ClientConfig.SkipVerifyCert,
},
},
},
}
if cfg.DevMode && !draftHandled {
draftHandled = true
srv.mux.Handle("/godraft:doc/", srv)
srv.mux.Handle("/godraft:docs/", srv)
srv.mux.Handle("/godraft:scheme/", srv)
srv.mux.Handle("/godraft:request/", srv)
}
return srv
}
func (e *apiGroupEntry) init(api *APIService) *apiGroupEntry {
if e.Scheme == nil && e.Type == "E" {
if route, ok := api.routes[e.Name]; ok {
s := route.ctrl.GetScheme().ToJSON()
e.Scheme = &s
}
}
for _, ne := range e.Entries {
ne.init(api)
}
return e
}
func isHTTPHandler(handler http.Handler) bool {
if handler != nil {
if v, ok := handler.(http.HandlerFunc); ok {
return v != nil
}
if v, ok := handler.(http.Handler); ok {
return v != nil
}
}
return false
}
func findGroupHandler(u string, list []GroupHandler, def http.HandlerFunc) http.HandlerFunc {
for _, gh := range list {
if gh == nil {
continue
}
for _, gu := range gh.Routes() {
if gu == u {
return gh.ServeHTTP
}
}
}
return def
}