init push
This commit is contained in:
54
internal/app/api/server.go
Normal file
54
internal/app/api/server.go
Normal file
@@ -0,0 +1,54 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user