/
http.go
201 lines (168 loc) · 4.75 KB
/
http.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
package server
import (
"context"
"database/sql"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/galexrt/fivenet/pkg/config"
"github.com/galexrt/fivenet/pkg/grpc/auth"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-contrib/static"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
tracesdk "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
"go.uber.org/fx"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var HTTPServerModule = fx.Module("httpserver",
fx.Provide(
New,
),
fx.Decorate(wrapLogger),
)
type HTTPServer *http.Server
type Params struct {
fx.In
LC fx.Lifecycle
Logger *zap.Logger
Config *config.Config
Engine *gin.Engine
}
type Result struct {
fx.Out
Server HTTPServer
}
func wrapLogger(log *zap.Logger) *zap.Logger {
return log.Named("http_server")
}
// New builds an HTTP server that will begin serving requests
// when the Fx application starts.
func New(p Params) (Result, error) {
// Create HTTP Server for graceful shutdown handling
srv := &http.Server{
Addr: p.Config.HTTP.Listen,
Handler: p.Engine,
}
p.LC.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
return err
}
p.Logger.Info("http server listening", zap.String("address", srv.Addr))
go srv.Serve(ln)
return nil
},
OnStop: func(ctx context.Context) error {
return srv.Shutdown(ctx)
},
})
return Result{
Server: srv,
}, nil
}
var HTTPEngineModule = fx.Module("httpengine",
fx.Provide(
NewEngine,
),
fx.Decorate(wrapLogger),
)
type EngineParams struct {
fx.In
Logger *zap.Logger
Config *config.Config
DB *sql.DB
TP *tracesdk.TracerProvider
TokenMgr *auth.TokenMgr
Services []Service `group:"httpservices"`
}
func NewEngine(p EngineParams) *gin.Engine {
// Gin HTTP Server
gin.SetMode(p.Config.Mode)
e := gin.New()
// Add Zap Logger to Gin
e.Use(ginzap.GinzapWithConfig(p.Logger, &ginzap.Config{
UTC: true,
TimeFormat: time.RFC3339,
Context: ginzap.Fn(func(c *gin.Context) []zapcore.Field {
fields := []zapcore.Field{}
// log request ID
if requestID := c.Writer.Header().Get("X-Request-Id"); requestID != "" {
fields = append(fields, zap.String("request_id", requestID))
}
// log trace and span ID
if trace.SpanFromContext(c.Request.Context()).SpanContext().IsValid() {
fields = append(fields, zap.String("traceId", trace.SpanFromContext(c.Request.Context()).SpanContext().TraceID().String()))
fields = append(fields, zap.String("spanId", trace.SpanFromContext(c.Request.Context()).SpanContext().SpanID().String()))
}
return fields
}),
}))
e.Use(ginzap.RecoveryWithZap(p.Logger, true))
// Sessions
sessStore := cookie.NewStore([]byte(p.Config.HTTP.Sessions.CookieSecret))
sessStore.Options(sessions.Options{
Domain: p.Config.HTTP.Sessions.Domain,
Path: "/",
MaxAge: int((24 * time.Hour).Seconds()),
HttpOnly: true,
Secure: true,
})
e.Use(sessions.SessionsMany([]string{"fivenet_oauth2_state"}, sessStore))
// Tracing
e.Use(otelgin.Middleware("fivenet", otelgin.WithTracerProvider(p.TP), otelgin.WithFilter(func(r *http.Request) bool {
// Skip `/images/*` requests
return !strings.HasPrefix(r.URL.Path, "/images/")
})))
e.Use(InjectToHeaders(p.TP))
for _, service := range p.Services {
if service == nil {
continue
}
service.RegisterHTTP(e)
}
// Setup nuxt generated files serving
frontendFS := static.LocalFile(".output/public/", true)
fileServer := http.FileServer(frontendFS)
// Register output dir for assets and other static files
e.Use(static.Serve("/", frontendFS))
// Setup not found handler
notFoundPage := []byte("404 page not found")
notFoundPageFile, err := frontendFS.Open("404.html")
if err != nil {
p.Logger.Error("failed to open 404.html file, falling back to 404 text page", zap.Error(err))
} else {
notFoundPage, err = io.ReadAll(notFoundPageFile)
if err != nil {
p.Logger.Error("failed to read 404.html file contents", zap.Error(err))
}
}
e.NoRoute(func(c *gin.Context) {
requestPath := c.Request.URL.Path
if strings.HasPrefix(requestPath, "/api") || requestPath == "/" {
return
}
// If the target is a directory (e.g., `/livemap`), load root `index.html``
if strings.HasSuffix(requestPath, "/") || !strings.Contains(requestPath, ".") {
c.Request.URL.Path = "/"
fileServer.ServeHTTP(c.Writer, c.Request)
c.Abort()
return
}
// Check if file exists
if frontendFS.Exists("/", c.Request.URL.Path) {
fileServer.ServeHTTP(c.Writer, c.Request)
} else {
c.Data(http.StatusNotFound, "text/html; charset=utf-8", notFoundPage)
}
c.Abort()
})
return e
}