-
Notifications
You must be signed in to change notification settings - Fork 1
/
gomek.go
417 lines (381 loc) · 10.2 KB
/
gomek.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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package gomek
import (
"context"
"errors"
"fmt"
"log"
"net/http"
)
const (
DEFAULT_BASE_TEMPLATE = "layout"
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 5000
DEFAULT_PROTOCOL = "http"
)
var (
DEFAULT_METHODS = []string{"GET"}
)
// Data type used to reference the data reference from the handler args
//
// func MyHandler(w http.ResponseWriter, r *http.Request, d *gomek.Data) {
// *d = map[string]string{ "v": "k"}
type Data map[string]interface{}
// CurrentView is a custom type representing the http.HandlerFunc type.
type CurrentView func(http.ResponseWriter, *http.Request, *Data)
type Handle func(pattern string, handler http.Handler)
type Middleware []func(http.Handler) http.HandlerFunc
// Config type that should be passed to `gomek.New`
type Config struct {
BaseTemplateName string
BaseTemplates []string
}
type Resource interface {
Delete(http.ResponseWriter, *http.Request, *Data)
Get(http.ResponseWriter, *http.Request, *Data)
Post(http.ResponseWriter, *http.Request, *Data)
Put(http.ResponseWriter, *http.Request, *Data)
}
type IApp interface {
resetCurrentView()
cloneRoute()
Start() error
SetHost(host string)
Listen(port int)
Methods(methods ...string) *App
Route(route string) *App
Templates(templates ...string)
BaseTemplates(templates ...string)
View(view CurrentView) *App
Resource(m Resource) *App
Use(h func(http.Handler) http.HandlerFunc)
Shutdown()
GetView() *View
GetConfig() *Config
}
type App struct {
baseTemplateName string
baseTemplates []string
Config Config
currentRoute string
currentMethods []string
currentTemplates []string
currentView CurrentView
currentResource Resource
Mux *http.ServeMux
Host string
Port int
Protocol string
view View
Handle Handle
middleware Middleware
rootCtx context.Context
authCtx context.Context
server *http.Server
}
func createAddr(a *App) string {
return fmt.Sprintf("%s:%d", a.Host, a.Port)
}
func (a *App) GetView() *View {
return &a.view
}
func (a *App) GetConfig() *Config {
return &a.Config
}
func (a *App) setup() *http.Server {
var auth = map[string]string{}
// Set app context
a.rootCtx = context.Background()
a.authCtx = context.WithValue(a.rootCtx, "auth", auth)
// Store the last registered view
if a.currentResource != nil {
a.view.StoreResource(a)
// Duplicate the resource methods for /<path_name>/ to /<path_name>
// This is because Go's http package swaps out POSTs to GETS with a /<path_name>/ path.
a.cloneRoute()
} else {
a.view.Store(a)
}
if len(a.currentMethods) < 1 {
a.currentMethods = DEFAULT_METHODS
}
a.resetCurrentView()
// Handle defaults
if a.Config.BaseTemplateName == "" {
a.Config.BaseTemplateName = DEFAULT_BASE_TEMPLATE
}
if a.Host == "" {
a.Host = DEFAULT_HOST
}
if a.Port == 0 {
a.Port = DEFAULT_PORT
}
if a.Protocol == "" {
a.Protocol = DEFAULT_PROTOCOL
}
// Create views
for _, v := range a.view.StoredViews {
a.view.Create(&a.Config, &a.middleware, a.Mux, v)
}
// Create the origin
address := createAddr(a)
// Server
return &http.Server{
Addr: address,
Handler: a.Mux,
TLSConfig: nil,
ReadTimeout: 0,
ReadHeaderTimeout: 0,
WriteTimeout: 0,
IdleTimeout: 0,
MaxHeaderBytes: 0,
TLSNextProto: nil,
ConnState: nil,
ErrorLog: nil,
BaseContext: nil,
ConnContext: nil,
}
}
func (a *App) resetCurrentView() {
a.currentRoute = ""
a.currentMethods = nil
a.baseTemplates = nil
a.currentView = nil
}
func (a *App) cloneRoute() {
// Duplicate the resource methods for /<path_name>/ to /<path_name>
// This is because Go's http package swaps out POSTs to GETS with a /<path_name>/ path.
if a.currentRoute[len(a.currentRoute)-1:] == ">" {
for _, m := range a.currentMethods {
if m == "POST" {
// Construct a path name from the stored `registeredRoute` value
for _, storedView := range a.view.StoredViews {
if storedView.registeredRoute == a.currentRoute {
// Create a route without the slash at the parth end e.g /<path_name>
a.currentRoute = fmt.Sprintf("/%s", storedView.rootName)
a.view.StoreResource(a)
}
}
break
}
}
}
}
// SetHost sets the host. Default is ":"
// If no port is set, then Gomek will default to `5000`
//
// app.SetHost("localhost")
func (a *App) SetHost(host string) {
a.Host = host
}
// Listen sets the port the server will accept request on.
// If no port is set, then Gomek will default to `5000`
//
// app.Listen(5001)
func (a *App) Listen(port int) {
a.Port = port
}
// Methods CRUD methods to match on the request URL. If there are no methods
// declared, then it defaults to - `"GET"`
// For Example
//
// app.Methods("GET")
// app.Methods("GET", "POST", "DELETE")
func (a *App) Methods(methods ...string) *App {
if len(methods) == 0 {
methods = append(methods, "GET")
}
// Add OPTIONS
methods = append(methods, "OPTIONS")
a.currentMethods = methods
return a
}
// Route A string representing the incoming request URL.
// This is the first argument to Gomek's Mux.Route() method or the first
// argument to http.HandleFunc(). For Example
//
// app.Route("/") // ... other chained methods
func (a *App) Route(route string) *App {
if a.currentRoute != "" {
// Store the previous view to lazily register them at run time
if a.currentResource != nil {
a.view.StoreResource(a)
//a.cloneRoute()
} else {
a.view.Store(a)
}
}
// This route gets registered in the Start method
a.currentRoute = route
return a
}
// Templates Method that takes a single template relative path or multiple template
// path slices of main route templates (not partial templates). For example:
//
// app.Route("/")
// .View(Home)
// .Methods("GET")
// .Templates("./templates/hero.html", "./templates/routes/home.html")
//
// The above example adds a `hero.html` partial template & a main route `home.html` template.
func (a *App) Templates(templates ...string) {
a.currentTemplates = templates
}
// BaseTemplates method accepts slices of string, string if the name of the
// template file.
//
// baseTemplates := []string{
// "./templates/layout.html",
// "./templates/sidebar.html",
// "./templates/navbar.html",
// "./templates/footer.html",
// }
// app.BaseTemplate(baseTemplates)
func (a *App) BaseTemplates(templates ...string) {
a.Config.BaseTemplates = templates
}
// View is called if the Route request URL is matched.
// handler arg is your View function.Create a View - template data needs to be passed
// by value to `data *map[string]interface{}`
//
// func Home(w http.ResponseWriter, r *http.Request, data *gomek.Data) {
// var templateData gomek.Data // Or map[string]interface{} .etc... // Create a map to store your template data
// templateData = make(map[string]interface{})
// templateData["heading"] = "Create a new advert"
// *data = templateData // pass by value back to `data`
// }
//
// app.
// // ...
// .View(Home)
// // ...
func (a *App) View(view CurrentView) *App {
a.currentView = view
return a
}
// Resource accepts a type that implements the `Resource` interface.
// This is useful for Rest design handler methods attached to a named resource
// type.
//
// type Notice struct {
// }
//
// func (n *Notice) Post(w http.ResponseWriter, request *http.Request, data *gomek.Data) {
// panic("implement me")
// }
//
// func (n *Notice) Put(w http.ResponseWriter, request *http.Request, data *gomek.Data) {
// panic("implement me")
// }
//
// func (n *Notice) Delete(w http.ResponseWriter, r *http.Request, d *gomek.Data) {
// panic("implement me")
// }
//
// func (n *Notice) Get(w http.ResponseWriter, r *http.Request, d *gomek.Data) {
// var notice schemas.Notice
// notice.Name = "Joe!"
// gomek.JSON(w, notice, http.StatusOK)
// }
//
// To use your implentation of the `Resource` type
//
// app.Route("/notices").Resource(&routes.Notice{}).Methods("GET")
func (a *App) Resource(m Resource) *App {
a.currentResource = m
return a
}
// Use adds middleware.
//
// app := gomek.New(gomek.Config{})
// app.Use(gomek.CORS)
func (a *App) Use(h func(http.Handler) http.HandlerFunc) {
a.middleware = append(a.middleware, h)
}
// Shutdown force shutdown of the Mux server
//
// app.Shutdown()
func (a *App) Shutdown() {
err := a.server.Shutdown(a.rootCtx)
if err != nil {
log.Fatalln("error shutting down", err)
}
}
// Args access the request arguments in a handler as a map
//
// args := gomek.Args(r)
func Args(r *http.Request) map[string]string {
if vars := r.Context().Value("uriArgs"); vars != nil {
return vars.(map[string]string)
}
return nil
}
// GetParams returns slices of string
//
// // example request url - http://127.0.0.1:8080/users?user_id=1
// userID, err := gomek.QueryParams(r, "user_id")
// if err != nil {
// log.Println("no user_id in params")
// return
// }
// // userID[0] = "1"
func GetParams(r *http.Request, name string) ([]string, error) {
params := r.URL.Query()
paramValue, present := params[name]
if !present || len(paramValue) == 0 {
log.Println("no noticeboardID in params")
return nil, errors.New("param not" + name + " present")
}
return paramValue, nil
}
// App
type _App struct {
*App
}
// Start sets up all the registered views, templates & middleware
//
// app = gomek.New(gomek.Config{})
// app.Start()
func (a *App) Start() error {
// Start server...
a.server = a.setup()
log.Printf("Starting server on %s://%s", a.Protocol, a.server.Addr)
err := a.server.ListenAndServe()
if err != nil {
log.Println("error starting gomek server", err)
} else {
log.Printf("Starting server on %s://%s", a.Protocol, a.server.Addr)
}
return err
}
// New creates a new gomek application
//
// app := gomek.New(gomek.Config{})
func New(config Config) *App {
mux := http.NewServeMux()
return &App{
Config: config,
Mux: mux,
Handle: mux.Handle,
}
}
type TestApp struct {
App
}
// NewTestApp creates a new gomek application
//
// app := gomek.NewTestApp(gomek.Config{})
func NewTestApp(config Config) IApp {
mux := http.NewServeMux()
app := TestApp{
App{
Config: config,
Mux: mux,
Handle: mux.Handle,
},
}
return &app
}
func (a *TestApp) Start() error {
a.App.setup()
return nil
}