-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathserve.go
177 lines (151 loc) · 4.89 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
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
package fuego
import (
"html/template"
"log/slog"
"net"
"net/http"
"reflect"
"time"
"github.com/getkin/kin-openapi/openapi3"
)
// 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 {
if err := s.setup(); err != nil {
return err
}
return s.Server.Serve(s.listener)
}
// 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
if err := s.setup(); err != nil {
return err
}
return s.Server.ServeTLS(s.listener, certFile, keyFile)
}
func (s *Server) setup() error {
if err := s.setupDefaultListener(); err != nil {
return err
}
if !s.OpenAPI.Config.DisableDefaultServer {
s.OpenAPI.Description().Servers = append(s.OpenAPI.Description().Servers, &openapi3.Server{
URL: s.url(),
Description: "local server",
})
}
go s.OutputOpenAPISpec()
s.Engine.RegisterOpenAPIRoutes(s)
s.printStartupMessage()
s.Server.Handler = s.Mux
for _, middleware := range s.globalMiddlewares {
s.Server.Handler = middleware(s.Server.Handler)
}
return nil
}
func (s *Server) setupDefaultListener() error {
if s.listener != nil {
s.Addr = s.listener.Addr().String()
return nil
}
listener, err := net.Listen("tcp", s.Addr)
s.listener = listener
return err
}
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)
}
}
// ContextFlowable 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)
}
// Flow is 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", "transformOut", timeAfterTransformOut.Sub(timeTransformOut)}.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())
}