This commit is contained in:
PB
2023-10-01 21:35:21 +02:00
parent 380fe41d1a
commit 1909744c79
23 changed files with 790 additions and 320 deletions

View File

@@ -2,8 +2,10 @@ package server
import (
"log"
"net"
"os"
"os/signal"
"strconv"
"syscall"
"time"
@@ -18,21 +20,21 @@ type (
*Config
addr string // e.g. "127.0.0.1:8080"
// name string // e.g. "awesome-rest-api"
// kvNmspc string
PurgeFn
}
HeaderRequestID struct {
RequestID string `reqHeader:"x-request-id"`
}
OptionFn func(*Server) error
PurgeFn func(*Server) error
PurgeFn func() error
)
func New(conf *Config) *Server {
return &Server{
App: fiber.New(fiber.Config{
AppName: conf.AppID,
ServerHeader: conf.AppName,
ServerHeader: conf.AppName + ":" + conf.AppID,
ReadTimeout: conf.ReadTimeout * time.Millisecond,
WriteTimeout: conf.WriteTimeout * time.Millisecond,
IdleTimeout: conf.IdleTimeout * time.Millisecond,
@@ -42,20 +44,25 @@ func New(conf *Config) *Server {
}
}
func (s *Server) Start(while chan struct{}, prgFn PurgeFn) error {
func (s *Server) Start(while chan struct{}) error {
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-sigint
if err := prgFn(s); err != nil {
if err := s.PurgeFn(); err != nil {
log.Fatalf("Failed to shutdown server. Reason: %v\n", err)
}
close(while)
}()
err := s.Listen(s.addr)
run := s.createRunFile("/app.run") // TODO move to common library (shared between server and worker)
defer s.removeRunFile(run)
ln, _ := net.Listen("tcp", s.addr)
// ln = tls.NewListener(ln, s.App.Server().TLSConfig)
err := s.Listener(ln)
if err != nil {
log.Fatalf("Failed to start server: %s. Reason: %v\n", s.Config.AppID, err)
close(while)
@@ -77,3 +84,18 @@ func (s *Server) GetRequestID(c *fiber.Ctx) (string, error) {
func (s *Server) Error(c *fiber.Ctx, code int, msg string) error {
return c.Status(code).JSON(http.ErrorResponse{Error: msg})
}
func (s *Server) createRunFile(path string) *os.File {
run, err := os.Create(path)
if err != nil {
log.Fatalf("Failed to create run file. Reason: %v\n", err)
os.Exit(1)
}
run.WriteString(strconv.Itoa(os.Getpid()))
return run
}
func (s *Server) removeRunFile(f *os.File) error {
return f.Close()
}