Yimaru-BackEnd/internal/web_server/server.go
2025-03-26 23:50:19 +03:00

77 lines
1.3 KiB
Go

package httpserver
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
type App struct {
port int
Router *http.ServeMux
logger *slog.Logger
notificationSecret string
}
func NewApp(
port int, logger *slog.Logger,
notificationSecret string,
) *App {
a := &App{
Router: http.NewServeMux(),
logger: logger,
port: port,
notificationSecret: notificationSecret,
}
a.initAppRoutes()
return a
}
func (a *App) Run() error {
srv := &http.Server{
Addr: fmt.Sprintf(":%s", strconv.Itoa(a.port)),
Handler: a.Router,
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
shutdownError := make(chan error)
go func() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
a.logger.Info("shutting down server")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
shutdownError <- srv.Shutdown(ctx)
}()
err := srv.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
return err
}
err = <-shutdownError
if err != nil {
return err
}
a.logger.Info("server stopped")
return nil
}
func (a *App) initAppRoutes() {
// a.Router.HandleFunc("/users",)
}