Files
fm_be/internal/app/api/server.go
2026-07-16 22:16:45 +07:00

55 lines
976 B
Go

package api
import (
"context"
"time"
"github.com/gofiber/fiber/v2"
)
type Server struct {
app *fiber.App
shutdownTimeout time.Duration
}
type ServerOption func(*Server)
const defaultShutdownTimeout = 30 * time.Second
func WithShutdownTimeout(timeout time.Duration) ServerOption {
return func(s *Server) {
if timeout > 0 {
s.shutdownTimeout = timeout
}
}
}
func NewServer(app *fiber.App, opts ...ServerOption) *Server {
srv := &Server{
app: app,
shutdownTimeout: defaultShutdownTimeout,
}
for _, opt := range opts {
if opt != nil {
opt(srv)
}
}
return srv
}
func (s *Server) Start(addr string) error {
return s.app.Listen(addr)
}
func (s *Server) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
if s.shutdownTimeout > 0 {
shutdownCtx, cancel := context.WithTimeout(ctx, s.shutdownTimeout)
defer cancel()
ctx = shutdownCtx
}
return s.app.ShutdownWithContext(ctx)
}