server.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/go-chi/chi/v5"
  7. "github.com/porter-dev/porter/api/server/shared/config/env"
  8. )
  9. // PorterAPIServer contains the routing and configuration options for starting the PorterAPIServer
  10. type PorterAPIServer struct {
  11. // Port is the port that PorterAPIServer listens on
  12. Port int
  13. // Router is the router that handles requests
  14. Router *chi.Mux
  15. // ServerConf is the server configuration
  16. ServerConf *env.ServerConf
  17. }
  18. // ListenAndServe starts the Porter API server
  19. func (p PorterAPIServer) ListenAndServe(ctx context.Context) error {
  20. ctx, cancel := context.WithCancel(ctx)
  21. defer cancel()
  22. address := fmt.Sprintf(":%d", p.Port)
  23. srv := &http.Server{
  24. Addr: address,
  25. Handler: p.Router,
  26. ReadTimeout: p.ServerConf.TimeoutRead,
  27. WriteTimeout: p.ServerConf.TimeoutWrite,
  28. IdleTimeout: p.ServerConf.TimeoutIdle,
  29. }
  30. defer srv.Shutdown(ctx) // nolint:errcheck
  31. errChan := make(chan error)
  32. go func() {
  33. err := srv.ListenAndServe()
  34. if err != nil {
  35. errChan <- err
  36. }
  37. }()
  38. select {
  39. case err := <-errChan:
  40. return err
  41. case <-ctx.Done():
  42. }
  43. return nil
  44. }