55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
package bootstrap
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type Config struct {
|
|
Addr string
|
|
ReadHeaderTimeout time.Duration
|
|
RegisterRoutes func(mux *http.ServeMux)
|
|
WrapHandler func(next http.Handler) http.Handler
|
|
StartWatchers func(ctx context.Context)
|
|
}
|
|
|
|
func Run(ctx context.Context, cfg Config) error {
|
|
if cfg.RegisterRoutes == nil {
|
|
return fmt.Errorf("register routes callback is required")
|
|
}
|
|
if cfg.Addr == "" {
|
|
return fmt.Errorf("addr is required")
|
|
}
|
|
|
|
readHeaderTimeout := cfg.ReadHeaderTimeout
|
|
if readHeaderTimeout <= 0 {
|
|
readHeaderTimeout = 5 * time.Second
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
cfg.RegisterRoutes(mux)
|
|
|
|
handler := http.Handler(mux)
|
|
if cfg.WrapHandler != nil {
|
|
handler = cfg.WrapHandler(handler)
|
|
}
|
|
|
|
srv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: handler,
|
|
ReadHeaderTimeout: readHeaderTimeout,
|
|
}
|
|
|
|
if cfg.StartWatchers != nil {
|
|
go cfg.StartWatchers(ctx)
|
|
}
|
|
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|