starter.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package internal
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "github.com/wuntsong-org/go-zero-plus/core/logx"
  8. "github.com/wuntsong-org/go-zero-plus/core/proc"
  9. "github.com/wuntsong-org/go-zero-plus/internal/health"
  10. )
  11. const probeNamePrefix = "rest"
  12. // StartOption defines the method to customize http.Server.
  13. type StartOption func(svr *http.Server)
  14. // StartHttp starts a http server.
  15. func StartHttp(ch chan *http.Server, host string, port int, handler http.Handler, opts ...StartOption) error {
  16. return start(host, port, handler, func(svr *http.Server) error {
  17. if ch != nil {
  18. ch <- svr
  19. }
  20. return svr.ListenAndServe()
  21. }, opts...)
  22. }
  23. // StartHttps starts a https server.
  24. func StartHttps(ch chan *http.Server, host string, port int, certFile, keyFile string, handler http.Handler,
  25. opts ...StartOption) error {
  26. return start(host, port, handler, func(svr *http.Server) error {
  27. if ch != nil {
  28. ch <- svr
  29. }
  30. // certFile and keyFile are set in buildHttpsServer
  31. return svr.ListenAndServeTLS(certFile, keyFile)
  32. }, opts...)
  33. }
  34. func start(host string, port int, handler http.Handler, run func(svr *http.Server) error,
  35. opts ...StartOption) (err error) {
  36. server := &http.Server{
  37. Addr: fmt.Sprintf("%s:%d", host, port),
  38. Handler: handler,
  39. }
  40. for _, opt := range opts {
  41. opt(server)
  42. }
  43. healthManager := health.NewHealthManager(fmt.Sprintf("%s-%s:%d", probeNamePrefix, host, port))
  44. waitForCalled := proc.AddShutdownListener(func() {
  45. healthManager.MarkNotReady()
  46. if e := server.Shutdown(context.Background()); e != nil {
  47. logx.Error(e)
  48. }
  49. })
  50. defer func() {
  51. if errors.Is(err, http.ErrServerClosed) {
  52. waitForCalled()
  53. }
  54. }()
  55. healthManager.MarkReady()
  56. health.AddProbe(healthManager)
  57. return run(server)
  58. }