runStaticFileServer creates a web server serving static files
(fileSys fs.FS, dir, port string, conf lib.Config)
| 343 | |
| 344 | // runStaticFileServer creates a web server serving static files |
| 345 | func (s *Server) runStaticFileServer(fileSys fs.FS, dir, port string, conf lib.Config) { |
| 346 | // Attempt to get a sub-filesystem rooted at the specified directory |
| 347 | distFS, err := fs.Sub(fileSys, dir) |
| 348 | if err != nil { |
| 349 | s.logger.Error(fmt.Sprintf("an error occurred running the static file server for %s: %s", dir, err.Error())) |
| 350 | return |
| 351 | } |
| 352 | |
| 353 | // Create a new ServeMux to handle incoming HTTP requests |
| 354 | mux := http.NewServeMux() |
| 355 | |
| 356 | // Define a handler function for the root path |
| 357 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 358 | // serve `index.html` with dynamic config injection |
| 359 | if r.URL.Path == "/" || r.URL.Path == "/index.html" { |
| 360 | |
| 361 | // Construct the file path for `index.html` |
| 362 | filePath := path.Join(dir, "index.html") |
| 363 | |
| 364 | // Open the file and defer closing until the function exits |
| 365 | data, e := fileSys.Open(filePath) |
| 366 | if e != nil { |
| 367 | http.NotFound(w, r) |
| 368 | return |
| 369 | } |
| 370 | defer data.Close() |
| 371 | |
| 372 | // Read the content of `index.html` into a byte slice |
| 373 | htmlBytes, e := fs.ReadFile(fileSys, filePath) |
| 374 | if e != nil { |
| 375 | http.NotFound(w, r) |
| 376 | return |
| 377 | } |
| 378 | |
| 379 | // Inject the configuration into the HTML file content |
| 380 | injectedHTML := injectConfig(string(htmlBytes), conf) |
| 381 | |
| 382 | // Set the response header as HTML and write the injected content to the response |
| 383 | w.Header().Set("Content-Type", "text/html") |
| 384 | w.WriteHeader(http.StatusOK) |
| 385 | w.Write([]byte(injectedHTML)) |
| 386 | return |
| 387 | } |
| 388 | |
| 389 | // For all other requests, serve the files directly from the file system |
| 390 | http.FileServer(http.FS(distFS)).ServeHTTP(w, r) |
| 391 | }) |
| 392 | |
| 393 | // Start the HTTP server in a new goroutine and listen on the specified port |
| 394 | go func() { |
| 395 | // Log a fatal error if the server fails to start |
| 396 | s.logger.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), mux).Error()) |
| 397 | }() |
| 398 | } |
| 399 | |
| 400 | // injectConfig() injects the config.json into the HTML file |
| 401 | func injectConfig(html string, config lib.Config) string { |
no test coverage detected