-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.go
126 lines (81 loc) · 2.34 KB
/
core.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
package alf
import (
"bytes"
"errors"
"fmt"
misc "github.com/PiterWeb/Alf-Router/errors"
"github.com/pterm/pterm"
"github.com/pterm/pterm/putils"
"github.com/valyala/fasthttp"
)
func App(config *AppConfig) error { // creates the app and starts it
if config.Port == "" {
config.Port = "8080"
}
if config.NotFound == nil {
config.NotFound = func(ctx *Ctx) {
ctx.Response.SetStatusCode(404)
ctx.WriteString("Path not found: ERROR 404")
}
}
for _, pl := range config.Plugins {
err := pl.Init_plugin(config)
if err != nil {
misc.ShowError(err.Error())
}
}
pterm.DefaultBigText.WithLetters(putils.LettersFromStringWithStyle("ALF", pterm.NewStyle(pterm.FgBlue))).Render()
pterm.Info.Println("Server running on port :" + config.Port)
errChan := make(chan error)
go func() {
errChan <- fasthttp.ListenAndServe(":"+config.Port, func(ctx *Ctx) {
handleRoute(ctx, config)
})
}()
go func() {
pterm.Info.Println("Press enter to stop the server: ")
fmt.Scanf("\n%c")
errChan <- errors.New("server stopped manually")
}()
return <-errChan
}
func handleRoute(ctx *Ctx, config *AppConfig) {
routes, methodFound := config.Routes[method(ctx.Method())]
if !methodFound {
return
}
var path string = string(ctx.Path())
if len(path) > 1 && path[len(path)-1] == '/' { // make /api equal to /api/
path = path[:len(path)-1]
}
route, pathFound := routes[path] // Intentar evitar la conversión de tipo del ctx.Path()
if !pathFound {
config.NotFound(ctx)
go misc.ShowWarning("Route not Found: " + string(ctx.Path()) + " [" + string(ctx.Method()) + "]")
return
}
if config.ServeStatic && (string(ctx.Method()) == "GET") {
staticPrefix := []byte("/static/")
staticHandler := fasthttp.FSHandler("/static", 1)
if bytes.HasPrefix(ctx.Path(), staticPrefix) {
staticHandler(ctx)
return
}
}
handleHeaders(ctx, &config.Headers)
next := true
handleMiddleware(ctx, &config.Middleware, &next) // handle global middleware
if route.Middleware != nil && next {
handleMiddleware(ctx, &route.Middleware, &next) // handle specific middleware
}
var errRoute error
if next {
errRoute = route.Handle(ctx)
}
if errRoute != nil {
ctx.Response.Reset()
route.Error(ctx, errRoute)
go misc.ShowError("Route Error (" + errRoute.Error() + ") caused on route: " + string(ctx.Path()))
return
}
}