platform: modularize api/gui, add docs-tests-web foundation, and refresh root config
This commit is contained in:
54
selective-vpn-api/app/bootstrap/server_runner.go
Normal file
54
selective-vpn-api/app/bootstrap/server_runner.go
Normal file
@@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user