-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
serve.go
148 lines (125 loc) · 4.2 KB
/
serve.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
package fuego
import (
"html/template"
"log/slog"
"net/http"
"reflect"
"time"
)
// Run starts the server.
// It is blocking.
// It returns an error if the server could not start (it could not bind to the port for example).
// It also generates the OpenAPI spec and outputs it to a file, the UI, and a handler (if enabled).
func (s *Server) Run() error {
s.setup()
return s.Server.ListenAndServe()
}
// RunTLS starts the server with a TLS listener
// It is blocking.
// It returns an error if the server could not start (it could not bind to the port for example).
// It also generates the OpenAPI spec and outputs it to a file, the UI, and a handler (if enabled).
func (s *Server) RunTLS(certFile, keyFile string) error {
s.isTLS = true
s.setup()
return s.Server.ListenAndServeTLS(certFile, keyFile)
}
func (s *Server) setup() {
go s.OutputOpenAPISpec()
s.printStartupMessage()
s.Server.Handler = s.Mux
if s.corsMiddleware != nil {
s.Server.Handler = s.corsMiddleware(s.Server.Handler)
}
}
func (s *Server) printStartupMessage() {
if !s.disableStartupMessages {
elapsed := time.Since(s.startTime)
slog.Debug("Server started in "+elapsed.String(), "info", "time between since server creation (fuego.NewServer) and server startup (fuego.Run). Depending on your implementation, there might be things that do not depend on fuego slowing start time")
slog.Info("Server running ✅ on "+s.url(), "started in", elapsed.String())
}
}
func (s *Server) proto() string {
if s.isTLS {
return "https"
}
return "http"
}
func (s *Server) url() string {
return s.proto() + "://" + s.Server.Addr
}
// HTTPHandler converts a Fuego controller into a http.HandlerFunc.
// Uses Server for configuration.
// Uses Route for route configuration. Optional.
func HTTPHandler[ReturnType, Body any](s *Server, controller func(c ContextWithBody[Body]) (ReturnType, error), route BaseRoute) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var templates *template.Template
if s.template != nil {
templates = template.Must(s.template.Clone())
}
// CONTEXT INITIALIZATION
ctx := NewNetHTTPContext[Body](route, w, r, readOptions{
DisallowUnknownFields: s.DisallowUnknownFields,
MaxBodySize: s.maxBodySize,
})
ctx.serializer = s.Serialize
ctx.errorSerializer = s.SerializeError
ctx.fs = s.fs
ctx.templates = templates
Flow(s.Engine, ctx, controller)
}
}
// Contains the logic for the flow of a Fuego controller.
// Extends ContextWithBody with methods not exposed in the Controllers.
type ContextFlowable[B any] interface {
ContextWithBody[B]
// SetDefaultStatusCode sets the status code of the response defined in the options.
SetDefaultStatusCode()
// Serialize serializes the given data to the response.
Serialize(data any) error
// SerializeError serializes the given error to the response.
SerializeError(err error)
}
// Generic handler for Fuego controllers.
func Flow[B, T any](s *Engine, ctx ContextFlowable[B], controller func(c ContextWithBody[B]) (T, error)) {
ctx.SetHeader("X-Powered-By", "Fuego")
ctx.SetHeader("Trailer", "Server-Timing")
timeCtxInit := time.Now()
// PARAMS VALIDATION
err := ValidateParams(ctx)
if err != nil {
err = s.ErrorHandler(err)
ctx.SerializeError(err)
return
}
timeController := time.Now()
ctx.SetHeader("Server-Timing", Timing{"fuegoReqInit", timeController.Sub(timeCtxInit), ""}.String())
// CONTROLLER
ans, err := controller(ctx)
if err != nil {
err = s.ErrorHandler(err)
ctx.SerializeError(err)
return
}
ctx.SetHeader("Server-Timing", Timing{"controller", time.Since(timeController), ""}.String())
ctx.SetDefaultStatusCode()
if reflect.TypeOf(ans) == nil {
return
}
// TRANSFORM OUT
timeTransformOut := time.Now()
ans, err = transformOut(ctx.Context(), ans)
if err != nil {
err = s.ErrorHandler(err)
ctx.SerializeError(err)
return
}
timeAfterTransformOut := time.Now()
ctx.SetHeader("Server-Timing", Timing{"transformOut", timeAfterTransformOut.Sub(timeTransformOut), "transformOut"}.String())
// SERIALIZATION
err = ctx.Serialize(ans)
if err != nil {
err = s.ErrorHandler(err)
ctx.SerializeError(err)
}
ctx.SetHeader("Server-Timing", Timing{"serialize", time.Since(timeAfterTransformOut), ""}.String())
}