generated from UCLALibrary/service-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
301 lines (247 loc) · 9.3 KB
/
main.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"errors"
"fmt"
"github.com/UCLALibrary/validation-service/api"
"github.com/UCLALibrary/validation-service/validation"
"github.com/UCLALibrary/validation-service/validation/config"
"github.com/UCLALibrary/validation-service/validation/utils"
"github.com/labstack/echo/v4"
middleware "github.com/oapi-codegen/echo-middleware"
"go.uber.org/zap"
"html/template"
"io"
"log"
"net/http"
"os"
"path/filepath"
"sync"
)
// Port is the default port for our server
const Port = 8888
// RouteMapping is a pairing of router path and file system path that can be used to configure request handlers.
type RouteMapping struct {
RoutePath string
FilePath string
}
// TemplateRenderer holds parsed HTML templates for the validation service's Web pages
type TemplateRenderer struct {
templates *template.Template
mu sync.Mutex
}
// Render function on our TemplateRenderer implements Echo's `Renderer` interface
func (renderer *TemplateRenderer) Render(writer io.Writer, name string, data interface{}, context echo.Context) error {
renderer.mu.Lock()
defer renderer.mu.Unlock()
return renderer.templates.ExecuteTemplate(writer, name, data)
}
// Service implements the generated OpenAPI interface (i.e., handles incoming requests)
type Service struct {
Engine *validation.Engine
}
// GetStatus handles the GET /status request
func (service *Service) GetStatus(context echo.Context) error {
// A placeholder response
return context.JSON(http.StatusOK, api.Status{
Service: "ok",
Fester: "ok",
FileSystem: "ok",
})
}
// UploadCSV handles the /upload/csv POST request
func (service *Service) UploadCSV(context echo.Context) error {
engine := service.Engine
logger := engine.GetLogger()
// Get the CSV file upload and profile
profile := context.FormValue("profile")
file, fileErr := context.FormFile("csvFile")
if fileErr != nil {
return context.JSON(http.StatusBadRequest, map[string]string{"error": "A CSV file must be uploaded"})
}
logger.Debug("Received uploaded CSV file",
zap.String("csvFile", file.Filename),
zap.String("profile", profile))
// Parse the CSV data
csvData, readErr := utils.ReadUpload(file, logger)
if readErr != nil {
return context.JSON(http.StatusBadRequest, map[string]string{"error": "Uploaded CSV file could not be parsed"})
}
if err := engine.Validate(profile, csvData); err != nil {
// Handle if there was a validation error
return context.JSON(http.StatusCreated, api.Status{
Service: fmt.Sprintf("error: %v", err),
Fester: "ok",
FileSystem: "ok",
})
}
// Handle if there were no validation errors
return context.JSON(http.StatusCreated, api.Status{
Service: "created",
Fester: "ok",
FileSystem: "ok",
})
}
// Main function starts our Echo server
func main() {
// Create a new validation engine for our service to use
engine, err := validation.NewEngine()
if err != nil {
log.Fatal(err)
}
// Get the validation engine's logger to use to configure Echo
logger := engine.GetLogger()
// Create a new validation application and configure its logger
echoApp := echo.New()
echoApp.Use(config.ZapLoggerMiddleware(logger))
// Hide application startup messages that don't play nicely with logger
echoApp.HideBanner = true
echoApp.HidePort = true
// Turn on Echo's debugging features if we're set to debug (mostly more info in errors)
if debugging := logger.Check(zap.DebugLevel, "Enable debugging"); debugging != nil {
echoApp.Debug = true
}
// Handle requests with and without a trailing slash using the trailingSlashMiddleware
echoApp.Pre(trailingSlashMiddleware)
// Configure the application's route handling
routes := append(configStaticRoutes(echoApp), configTemplateRoutes(echoApp, getTemplateRenderer(logger))...)
echoApp.Use(routerConfigMiddleware(echoApp, engine, routes))
// Log the configured routes when we're running in debug mode
if debugging := logger.Check(zap.DebugLevel, "Loading routes"); debugging != nil {
var fields []zap.Field
for _, route := range echoApp.Routes() {
routeInfo := []string{route.Method, route.Path}
fields = append(fields, zap.Strings("route", routeInfo))
}
logger.Debug("Registered routes", fields...)
}
// Configure the validation server with the port number and the Echo application
server := &http.Server{
Addr: fmt.Sprintf(":%d", Port),
Handler: echoApp,
}
// Start the validation server
if err := echoApp.StartServer(server); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Server failed: %v", err)
}
}
// getTemplateRenderer loads the HTML templates and then provides a template registry that can render them.
func getTemplateRenderer(logger *zap.Logger) *TemplateRenderer {
templates, templateErr := loadTemplates(logger)
if templateErr != nil {
logger.Error(templateErr.Error())
}
// Log all the HTML templates that were loaded if we're in debugging mode
if debugging := logger.Check(zap.DebugLevel, "Load templates"); debugging != nil && templates != nil {
var fields []zap.Field
for _, tmpl := range templates.Templates() {
// In loadTemplates we add a 'root' template with an empty name, but we delete it here it's not used
if tmpl.Name() != "" {
fields = append(fields, zap.String("template", tmpl.Name()))
}
}
logger.Debug("Loaded Web resources", fields...)
}
return &TemplateRenderer{templates: templates}
}
// loadTemplates loads the available HTML templates for the Web UI.
func loadTemplates(logger *zap.Logger) (*template.Template, error) {
templates := template.New("") // New set of templates
// We try both locations: the Docker container's and the local dev's
patterns := []string{
// The templates should exist in only one of these locations
"/usr/local/data/html/template/*.tmpl", // Docker templates
"html/template/*.tmpl", // Local templates
}
foundTemplates := false
// Parse each template path pattern so we can add any matches to the template set
for _, pattern := range patterns {
// Check if any files match the pattern before parsing them
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, fmt.Errorf("error checking pattern %s: %w", pattern, err)
}
// Skip this pattern if no template files are found here
if len(matches) == 0 {
logger.Debug("No templates found (Skipping)", zap.String("location", pattern))
continue // Moving on to the next location
}
// If we get this far, at least one location had templates
foundTemplates = true
// Attempt to parse the templates once we know they exist
templates, err = templates.ParseGlob(pattern)
if err != nil {
return nil, fmt.Errorf("error loading templates from %s: %w", pattern, err)
}
}
// If no templates were found in either location, return an error
if !foundTemplates {
return nil, fmt.Errorf("no templates found in any of the specified locations")
}
// Return the set of template matches
return templates, nil
}
// configStaticRoutes configures our static resources with the Echo application.
func configStaticRoutes(echoApp *echo.Echo) []RouteMapping {
staticRoutes := []RouteMapping{
{"/openapi.yml", "html/assets/openapi.yml"},
{"/validation.css", "html/assets/validation.css"},
{"/validation.js", "html/assets/validation.js"},
}
for _, route := range staticRoutes {
echoApp.GET(route.RoutePath, func(aContext echo.Context) error {
return aContext.File(route.FilePath)
})
}
return staticRoutes
}
// configTemplateRoutes configures our template resources with the Echo application.
func configTemplateRoutes(echoApp *echo.Echo, renderer *TemplateRenderer) []RouteMapping {
templateRoutes := []RouteMapping{
{"/", ""},
{"index.html", ""},
}
// Set the Echo application's default template renderer
echoApp.Renderer = renderer
// Have the templates renderer handle incoming index requests
echoApp.GET(templateRoutes[0].RoutePath, func(context echo.Context) error {
data := map[string]interface{}{
"Version": os.Getenv("VERSION"),
}
return context.Render(http.StatusOK, templateRoutes[1].RoutePath, data)
})
return templateRoutes
}
// routerConfigMiddleware configures the application's router with a fully configured OpenAPI set of routes.
func routerConfigMiddleware(echoApp *echo.Echo, engine *validation.Engine, routes []RouteMapping) echo.MiddlewareFunc {
swagger, swaggerErr := api.GetSwagger()
if swaggerErr != nil {
engine.GetLogger().Fatal("Failed to load OpenAPI spec", zap.Error(swaggerErr))
}
// Register OpenAPI defined request handlers for our service
api.RegisterHandlers(echoApp, &Service{
Engine: engine,
})
// We return the oapi-codegen middleware that handles our OpenAPI defined routes
return middleware.OapiRequestValidatorWithOptions(swagger, &middleware.Options{
Skipper: func(aContext echo.Context) bool {
for index, _ := range routes {
// We ignore paths that we've already configured through static or template handlers
if aContext.Path() == routes[index].RoutePath {
return true
}
}
return false
},
})
}
// trailingSlashMiddleware handles paths with slashes at the end so they also resolve.
func trailingSlashMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(context echo.Context) error {
path := context.Request().URL.Path
// Strip trailing slashes if found in path
if path != "/" && path[len(path)-1] == '/' {
context.Request().URL.Path = path[:len(path)-1]
}
return next(context)
}
}