-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
application.go
516 lines (453 loc) · 13.5 KB
/
application.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// 🚀 Fiber is an Express.js inspired web framework written in Go with 💖
// 📌 Please open an issue if you got suggestions or found a bug!
// 🖥 Links: https://github.com/gofiber/fiber, https://fiber.wiki
// 🦸 Not all heroes wear capes, thank you to some amazing people
// 💖 @valyala, @erikdubbelboer, @savsgio, @julienschmidt, @koddr
package fiber
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/reuseport"
)
const (
// Version : Fiber version
Version = "1.4.3"
banner = "\x1b[1;32m" + ` ______ __ ______ ______ ______
/\ ___\ /\ \ /\ == \ /\ ___\ /\ == \
\ \ __\ \ \ \ \ \ __< \ \ __\ \ \ __<
\ \_\ \ \_\ \ \_____\ \ \_____\ \ \_\ \_\
\/_/ \/_/ \/_____/ \/_____/ \/_/ /_/
` + "\x1b[1;30mFiber \x1b[1;32mv%s\x1b[1;30m %s on \x1b[1;32m%s\x1b[1;30m, visit \x1b[1;32m%s\x1b[0m\n\n"
//
)
var (
prefork = flag.Bool("prefork", false, "use prefork")
child = flag.Bool("child", false, "is child process")
)
// Application structure
type Application struct {
// Server name header
Server string
httpServer *fasthttp.Server
// Show fiber banner
Banner bool
// https://github.com/valyala/fasthttp/blob/master/server.go#L150
Engine *engine
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
Prefork bool
child bool
// Stores all routes
routes []*Route
}
// Fasthttp settings
// https://github.com/valyala/fasthttp/blob/master/server.go#L150
type engine struct {
Concurrency int
DisableKeepAlive bool
ReadBufferSize int
WriteBufferSize int
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxConnsPerIP int
MaxRequestsPerConn int
TCPKeepalive bool
TCPKeepalivePeriod time.Duration
MaxRequestBodySize int
ReduceMemoryUsage bool
GetOnly bool
DisableHeaderNamesNormalizing bool
SleepWhenConcurrencyLimitsExceeded time.Duration
NoDefaultContentType bool
KeepHijackedConns bool
}
// New https://fiber.wiki/application#new
func New() *Application {
flag.Parse()
return &Application{
Server: "",
httpServer: nil,
Banner: true,
Prefork: *prefork,
child: *child,
Engine: &engine{
Concurrency: 256 * 1024,
DisableKeepAlive: false,
ReadBufferSize: 4096,
WriteBufferSize: 4096,
WriteTimeout: 0,
ReadTimeout: 0,
IdleTimeout: 0,
MaxConnsPerIP: 0,
MaxRequestsPerConn: 0,
TCPKeepalive: false,
TCPKeepalivePeriod: 0,
MaxRequestBodySize: 4 * 1024 * 1024,
ReduceMemoryUsage: false,
GetOnly: false,
DisableHeaderNamesNormalizing: false,
SleepWhenConcurrencyLimitsExceeded: 0,
NoDefaultContentType: false,
KeepHijackedConns: false,
},
}
}
// Group :
type Group struct {
path string
app *Application
}
// Group :
func (app *Application) Group(path string) *Group {
return &Group{
path: path,
app: app,
}
}
// Connect establishes a tunnel to the server
// identified by the target resource.
func (app *Application) Connect(args ...interface{}) *Application {
app.register("CONNECT", args...)
return app
}
// Connect for group
func (grp *Group) Connect(args ...interface{}) *Group {
grp.register("CONNECT", args...)
return grp
}
// Put replaces all current representations
// of the target resource with the request payload.
func (app *Application) Put(args ...interface{}) *Application {
app.register("PUT", args...)
return app
}
// Put for group
func (grp *Group) Put(args ...interface{}) *Group {
grp.register("PUT", args...)
return grp
}
// Post is used to submit an entity to the specified resource,
// often causing a change in state or side effects on the server.
func (app *Application) Post(args ...interface{}) *Application {
app.register("POST", args...)
return app
}
// Post for group
func (grp *Group) Post(args ...interface{}) *Group {
grp.register("POST", args...)
return grp
}
// Delete deletes the specified resource.
func (app *Application) Delete(args ...interface{}) *Application {
app.register("DELETE", args...)
return app
}
// Delete for group
func (grp *Group) Delete(args ...interface{}) *Group {
grp.register("DELETE", args...)
return grp
}
// Head asks for a response identical to that of a GET request,
// but without the response body.
func (app *Application) Head(args ...interface{}) *Application {
app.register("HEAD", args...)
return app
}
// Head for group
func (grp *Group) Head(args ...interface{}) *Group {
grp.register("HEAD", args...)
return grp
}
// Patch is used to apply partial modifications to a resource.
func (app *Application) Patch(args ...interface{}) *Application {
app.register("PATCH", args...)
return app
}
// Patch for group
func (grp *Group) Patch(args ...interface{}) *Group {
grp.register("PATCH", args...)
return grp
}
// Options is used to describe the communication options
// for the target resource.
func (app *Application) Options(args ...interface{}) *Application {
app.register("OPTIONS", args...)
return app
}
// Options for group
func (grp *Group) Options(args ...interface{}) *Group {
grp.register("OPTIONS", args...)
return grp
}
// Trace performs a message loop-back test
// along the path to the target resource.
func (app *Application) Trace(args ...interface{}) *Application {
app.register("TRACE", args...)
return app
}
// Trace for group
func (grp *Group) Trace(args ...interface{}) *Group {
grp.register("TRACE", args...)
return grp
}
// Get requests a representation of the specified resource.
// Requests using GET should only retrieve data.
func (app *Application) Get(args ...interface{}) *Application {
app.register("GET", args...)
return app
}
// Get for group
func (grp *Group) Get(args ...interface{}) *Group {
grp.register("GET", args...)
return grp
}
// All matches any HTTP method
func (app *Application) All(args ...interface{}) *Application {
app.register("ALL", args...)
return app
}
// All for group
func (grp *Group) All(args ...interface{}) *Group {
grp.register("ALL", args...)
return grp
}
// Use only matches the starting path
func (app *Application) Use(args ...interface{}) *Application {
app.register("USE", args...)
return app
}
// Use for group
func (grp *Group) Use(args ...interface{}) *Group {
grp.register("USE", args...)
return grp
}
// Static https://fiber.wiki/application#static
func (app *Application) Static(args ...string) {
prefix := "/"
root := "./"
wildcard := false
// enable / disable gzipping somewhere?
// todo v2.0.0
gzip := true
if len(args) == 1 {
root = args[0]
} else if len(args) == 2 {
prefix = args[0]
root = args[1]
if prefix[0] != '/' {
prefix = "/" + prefix
}
}
// Check if wildcard for single files
// app.Static("*", "./public/index.html")
// app.Static("/*", "./public/index.html")
if prefix == "*" || prefix == "/*" {
wildcard = true
}
// Check if root exists
if _, err := os.Lstat(root); err != nil {
log.Fatal("Static: ", err)
}
// Lets get all files from root
files, _, err := getFiles(root)
if err != nil {
log.Fatal("Static: ", err)
}
// ./static/compiled => static/compiled
mount := filepath.Clean(root)
// Loop over all files
for _, file := range files {
// Ignore the .gzipped files by fasthttp
if strings.Contains(file, ".fasthttp.gz") {
continue
}
// Time to create a fake path for the route match
// static/index.html => /index.html
path := filepath.Join(prefix, strings.Replace(file, mount, "", 1))
// Store original file path to use in ctx handler
filePath := file
// If the file is an index.html, bind the prefix to index.html directly
if filepath.Base(filePath) == "index.html" || filepath.Base(filePath) == "index.htm" {
app.routes = append(app.routes, &Route{"GET", prefix, wildcard, false, nil, nil, func(c *Ctx) {
c.SendFile(filePath, gzip)
}})
}
// Add the route + SendFile(filepath) to routes
app.routes = append(app.routes, &Route{"GET", path, wildcard, false, nil, nil, func(c *Ctx) {
c.SendFile(filePath, gzip)
}})
}
}
// Listen : https://fiber.wiki/application#listen
func (app *Application) Listen(address interface{}, tls ...string) {
host := ""
switch val := address.(type) {
case int:
host = ":" + strconv.Itoa(val) // 8080 => ":8080"
case string:
if !strings.Contains(val, ":") {
val = ":" + val // "8080" => ":8080"
}
host = val
default:
log.Fatal("Listen: Host must be an INT port or STRING address")
}
// Create fasthttp server
app.httpServer = app.setupServer()
// Prefork enabled
if app.Prefork && runtime.NumCPU() > 1 {
if app.Banner && !app.child {
fmt.Printf(banner, Version, "preforking", host, "fiber.wiki")
}
app.prefork(host, tls...)
}
// Prefork disabled
if app.Banner {
fmt.Printf(banner, Version, "listening", host, "fiber.wiki")
}
ln, err := net.Listen("tcp4", host)
if err != nil {
log.Fatal("Listen: ", err)
}
// enable TLS/HTTPS
if len(tls) > 1 {
if err := app.httpServer.ServeTLS(ln, tls[0], tls[1]); err != nil {
log.Fatal("Listen: ", err)
}
}
if err := app.httpServer.Serve(ln); err != nil {
log.Fatal("Listen: ", err)
}
}
// Shutdown server gracefully
func (app *Application) Shutdown() error {
if app.httpServer == nil {
return fmt.Errorf("Server is not running")
}
return app.httpServer.Shutdown()
}
// Test takes a http.Request and execute a fake connection to the application
// It returns a http.Response when the connection was successfull
func (app *Application) Test(req *http.Request) (*http.Response, error) {
// Get raw http request
reqRaw, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
// Setup a fiber server struct
app.httpServer = app.setupServer()
// Create fake connection
conn := &conn{}
// Pass HTTP request to conn
_, err = conn.r.Write(reqRaw)
if err != nil {
return nil, err
}
// Serve conn to server
channel := make(chan error)
go func() {
channel <- app.httpServer.ServeConn(conn)
}()
// Wait for callback
select {
case err := <-channel:
if err != nil {
return nil, err
}
// Throw timeout error after 200ms
case <-time.After(500 * time.Millisecond):
return nil, fmt.Errorf("Timeout")
}
// Get raw HTTP response
respRaw, err := ioutil.ReadAll(&conn.w)
if err != nil {
return nil, err
}
// Create buffer
reader := strings.NewReader(getString(respRaw))
buffer := bufio.NewReader(reader)
// Convert raw HTTP response to http.Response
resp, err := http.ReadResponse(buffer, req)
if err != nil {
return nil, err
}
// Return *http.Response
return resp, nil
}
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
func (app *Application) prefork(host string, tls ...string) {
// Master proc
if !app.child {
// Create babies
childs := make([]*exec.Cmd, runtime.NumCPU())
// #nosec G204
for i := range childs {
childs[i] = exec.Command(os.Args[0], "-prefork", "-child")
childs[i].Stdout = os.Stdout
childs[i].Stderr = os.Stderr
if err := childs[i].Start(); err != nil {
log.Fatal("Listen-prefork: ", err)
}
}
for _, child := range childs {
if err := child.Wait(); err != nil {
log.Fatal("Listen-prefork: ", err)
}
}
os.Exit(0)
}
// Child proc
runtime.GOMAXPROCS(1)
ln, err := reuseport.Listen("tcp4", host)
if err != nil {
log.Fatal("Listen-prefork: ", err)
}
// enable TLS/HTTPS
if len(tls) > 1 {
if err := app.httpServer.ServeTLS(ln, tls[0], tls[1]); err != nil {
log.Fatal("Listen-prefork: ", err)
}
}
if err := app.httpServer.Serve(ln); err != nil {
log.Fatal("Listen-prefork: ", err)
}
}
func (app *Application) setupServer() *fasthttp.Server {
return &fasthttp.Server{
Handler: app.handler,
Name: app.Server,
Concurrency: app.Engine.Concurrency,
DisableKeepalive: app.Engine.DisableKeepAlive,
ReadBufferSize: app.Engine.ReadBufferSize,
WriteBufferSize: app.Engine.WriteBufferSize,
ReadTimeout: app.Engine.ReadTimeout,
WriteTimeout: app.Engine.WriteTimeout,
IdleTimeout: app.Engine.IdleTimeout,
MaxConnsPerIP: app.Engine.MaxConnsPerIP,
MaxRequestsPerConn: app.Engine.MaxRequestsPerConn,
TCPKeepalive: app.Engine.TCPKeepalive,
TCPKeepalivePeriod: app.Engine.TCPKeepalivePeriod,
MaxRequestBodySize: app.Engine.MaxRequestBodySize,
ReduceMemoryUsage: app.Engine.ReduceMemoryUsage,
GetOnly: app.Engine.GetOnly,
DisableHeaderNamesNormalizing: app.Engine.DisableHeaderNamesNormalizing,
SleepWhenConcurrencyLimitsExceeded: app.Engine.SleepWhenConcurrencyLimitsExceeded,
NoDefaultServerHeader: app.Server == "",
NoDefaultContentType: app.Engine.NoDefaultContentType,
KeepHijackedConns: app.Engine.KeepHijackedConns,
}
}