-
Notifications
You must be signed in to change notification settings - Fork 5
/
route.go
227 lines (197 loc) · 6.18 KB
/
route.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
package fiber
import (
"context"
"errors"
"fmt"
"net/http"
"reflect"
"runtime"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/template/html/v2"
"github.com/goravel/framework/contracts/config"
httpcontract "github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/contracts/route"
"github.com/goravel/framework/support"
"github.com/goravel/framework/support/color"
"github.com/goravel/framework/support/file"
"github.com/goravel/framework/support/json"
"github.com/savioxavier/termlink"
)
// Route fiber route
// Route fiber 路由
type Route struct {
route.Router
config config.Config
instance *fiber.App
}
// NewRoute create new fiber route instance
// NewRoute 创建新的 fiber 路由实例
func NewRoute(config config.Config, parameters map[string]any) (*Route, error) {
var views fiber.Views
if driver, exist := parameters["driver"]; exist {
template, ok := config.Get("http.drivers." + driver.(string) + ".template").(fiber.Views)
if ok {
views = template
} else {
templateCallback, ok := config.Get("http.drivers." + driver.(string) + ".template").(func() (fiber.Views, error))
if ok {
template, err := templateCallback()
if err != nil {
return nil, err
}
views = template
}
}
}
if views == nil && file.Exists("./resources/views") {
views = html.New("./resources/views", ".tmpl")
}
network := fiber.NetworkTCP
prefork := config.GetBool("http.drivers.fiber.prefork", false)
// Fiber not support prefork on dual stack
// https://docs.gofiber.io/api/fiber#config
if prefork {
network = fiber.NetworkTCP4
}
app := fiber.New(fiber.Config{
Prefork: prefork,
BodyLimit: config.GetInt("http.drivers.fiber.body_limit", 4096) << 10,
ReadBufferSize: config.GetInt("http.drivers.fiber.header_limit", 4096),
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
Network: network,
Views: views,
})
return &Route{
Router: NewGroup(
config,
app,
"",
[]httpcontract.Middleware{},
[]httpcontract.Middleware{},
),
config: config,
instance: app,
}, nil
}
// Fallback set fallback handler
// Fallback 设置回退处理程序
func (r *Route) Fallback(handler httpcontract.HandlerFunc) {
r.instance.Use(func(ctx *fiber.Ctx) error {
if response := handler(NewContext(ctx)); response != nil {
return response.Render()
}
return nil
})
}
// GlobalMiddleware set global middleware
// GlobalMiddleware 设置全局中间件
func (r *Route) GlobalMiddleware(middlewares ...httpcontract.Middleware) {
debug := r.config.GetBool("app.debug", false)
timeout := time.Duration(r.config.GetInt("http.request_timeout", 3)) * time.Second
fiberHandlers := []fiber.Handler{
recover.New(recover.Config{
EnableStackTrace: debug,
}),
}
if debug {
fiberHandlers = append(fiberHandlers, logger.New(logger.Config{
Format: "[HTTP] ${time} | ${status} | ${latency} | ${ip} | ${method} | ${path}\n",
TimeZone: r.config.GetString("app.timezone", "UTC"),
TimeFormat: "2006/01/02 - 15:04:05",
}))
}
globalMiddlewares := append([]httpcontract.Middleware{
Cors(), Timeout(timeout),
}, middlewares...)
fiberHandlers = append(fiberHandlers, middlewaresToFiberHandlers(globalMiddlewares)...)
r.setMiddlewares(fiberHandlers)
}
// Run run server
// Run 运行服务器
func (r *Route) Run(host ...string) error {
if len(host) == 0 {
defaultHost := r.config.GetString("http.host")
defaultPort := r.config.GetString("http.port")
if defaultPort == "" {
return errors.New("port can't be empty")
}
completeHost := defaultHost + ":" + defaultPort
host = append(host, completeHost)
}
r.outputRoutes()
color.Green().Println(termlink.Link("[HTTP] Listening and serving HTTP on", "http://"+host[0]))
return r.instance.Listen(host[0])
}
// RunTLS run TLS server
// RunTLS 运行 TLS 服务器
func (r *Route) RunTLS(host ...string) error {
if len(host) == 0 {
defaultHost := r.config.GetString("http.tls.host")
defaultPort := r.config.GetString("http.tls.port")
if defaultPort == "" {
return errors.New("port can't be empty")
}
completeHost := defaultHost + ":" + defaultPort
host = append(host, completeHost)
}
certFile := r.config.GetString("http.tls.ssl.cert")
keyFile := r.config.GetString("http.tls.ssl.key")
return r.RunTLSWithCert(host[0], certFile, keyFile)
}
// RunTLSWithCert run TLS server with cert file and key file
// RunTLSWithCert 使用证书文件和密钥文件运行 TLS 服务器
func (r *Route) RunTLSWithCert(host, certFile, keyFile string) error {
if host == "" {
return errors.New("host can't be empty")
}
if certFile == "" || keyFile == "" {
return errors.New("certificate can't be empty")
}
r.outputRoutes()
color.Green().Println(termlink.Link("[HTTPS] Listening and serving HTTPS on", "https://"+host))
return r.instance.ListenTLS(host, certFile, keyFile)
}
// Stop gracefully shuts down the server
// Stop 优雅退出HTTP Server
func (r *Route) Stop(ctx ...context.Context) error {
c := context.Background()
if len(ctx) > 0 {
c = ctx[0]
}
return r.instance.ShutdownWithContext(c)
}
// ServeHTTP serve http request (Not support)
// ServeHTTP 服务 HTTP 请求 (不支持)
func (r *Route) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
panic("not support")
}
// Test for unit test
// Test 用于单元测试
func (r *Route) Test(request *http.Request) (*http.Response, error) {
return r.instance.Test(request)
}
// outputRoutes output all routes
// outputRoutes 输出所有路由
func (r *Route) outputRoutes() {
if r.config.GetBool("app.debug") && support.Env != support.EnvArtisan {
for _, item := range r.instance.GetRoutes() {
for _, handler := range item.Handlers {
if strings.Contains(runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name(), "handlerToFiberHandler") {
fmt.Printf("%-10s %s\n", item.Method, colonToBracket(item.Path))
break
}
}
}
}
}
func (r *Route) setMiddlewares(middlewares []fiber.Handler) {
for _, middleware := range middlewares {
r.instance.Use(middleware)
}
}