96 lines
2.5 KiB
Go
96 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"embed"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/rs/zerolog"
|
|
"github.com/rs/zerolog/log"
|
|
"gitlab.com/mstarongitlab/goutils/embedFsWrapper"
|
|
"gitlab.com/mstarongitlab/goutils/middleware"
|
|
)
|
|
|
|
//go:embed frontend/dist
|
|
var frontendFS embed.FS
|
|
|
|
func main() {
|
|
setLogger()
|
|
setLogLevel()
|
|
|
|
serverHandler := http.NewServeMux()
|
|
serverHandler.Handle(
|
|
"/",
|
|
http.FileServerFS(embedFsWrapper.NewFSWrapper(frontendFS, "frontend/dist/")),
|
|
)
|
|
// serverHandler := server.NewServer(embedFsWrapper.NewFSWrapper(frontendFS, "frontend/dist/"))
|
|
server := http.Server{
|
|
Handler: middleware.ChainMiddlewares(serverHandler, middleware.LoggingMiddleware),
|
|
Addr: *flagAddr,
|
|
}
|
|
|
|
// Setup exit notifications
|
|
exitSignalChannel := make(chan os.Signal, 2)
|
|
signal.Notify(exitSignalChannel, os.Interrupt, syscall.SIGTERM)
|
|
|
|
// Start the server in a separate goroutine so that main can handle shutdown
|
|
go func() {
|
|
log.Info().Str("addr", server.Addr).Msg("Starting server")
|
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatal().Err(err).Msg("Server crashed!")
|
|
}
|
|
}()
|
|
|
|
// Wait for outside signal to close the server and stop the app
|
|
<-exitSignalChannel
|
|
|
|
// Close the server with a maximum timeout of 30 seconds
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
|
|
defer cancel()
|
|
log.Info().Msg("Shutting down server")
|
|
err := server.Shutdown(ctx)
|
|
if err != nil {
|
|
log.Fatal().Err(err).Msg("Failed to cleanly stop server")
|
|
}
|
|
|
|
}
|
|
|
|
func setLogger(extraLogWriters ...io.Writer) {
|
|
if !*flagJsonLogging {
|
|
console := zerolog.ConsoleWriter{Out: os.Stderr}
|
|
log.Logger = zerolog.New(zerolog.MultiLevelWriter(append([]io.Writer{console}, extraLogWriters...)...)).
|
|
With().
|
|
Timestamp().
|
|
Logger()
|
|
} else {
|
|
log.Logger = zerolog.New(zerolog.MultiLevelWriter(
|
|
append([]io.Writer{log.Logger}, extraLogWriters...)...,
|
|
)).With().Timestamp().Logger()
|
|
}
|
|
}
|
|
|
|
func setLogLevel() {
|
|
switch strings.ToLower(*flagLogLevel) {
|
|
case "trace":
|
|
zerolog.SetGlobalLevel(zerolog.TraceLevel)
|
|
case "debug":
|
|
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
|
case "info":
|
|
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
|
case "warn":
|
|
zerolog.SetGlobalLevel(zerolog.WarnLevel)
|
|
case "error":
|
|
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
|
|
case "fatal":
|
|
zerolog.SetGlobalLevel(zerolog.FatalLevel)
|
|
default:
|
|
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
|
}
|
|
log.Info().Str("new-level", *flagLogLevel).Msg("New log level set")
|
|
}
|