@@ -1,34 +1,61 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
port int
|
||||
cfg config.Cfg
|
||||
}
|
||||
|
||||
func NewServer() *http.Server {
|
||||
func Start(ctx context.Context, cfg config.Cfg) (err error) {
|
||||
port, _ := strconv.Atoi(os.Getenv("PORT"))
|
||||
if port == 0 {
|
||||
port = 8080
|
||||
}
|
||||
s := &Server{
|
||||
port: port,
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
// Declare Server config
|
||||
server := &http.Server{
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", s.port),
|
||||
Handler: s.RegisterRoutes(),
|
||||
IdleTimeout: time.Minute,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
}
|
||||
idleConnsClosed := make(chan struct{})
|
||||
|
||||
return server
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
|
||||
slog.Info("shutting down server")
|
||||
|
||||
// Shutdown server when ctx done
|
||||
if err = srv.Shutdown(context.Background()); err != nil {
|
||||
// Error from closing listeners, or context timeout:
|
||||
err = fmt.Errorf("error whilse shutting down server: %w", err)
|
||||
}
|
||||
|
||||
close(idleConnsClosed)
|
||||
}()
|
||||
|
||||
slog.Info("starting server", "address", srv.Addr)
|
||||
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
|
||||
return fmt.Errorf("error while server ListenAndServe: %w", err)
|
||||
}
|
||||
|
||||
<-idleConnsClosed
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user