starter.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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(host string, port int, handler http.Handler, opts ...StartOption) error {
  16. return start(host, port, handler, func(svr *http.Server) error {
  17. return svr.ListenAndServe()
  18. }, opts...)
  19. }
  20. // StartHttps starts a https server.
  21. func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler,
  22. opts ...StartOption) error {
  23. return start(host, port, handler, func(svr *http.Server) error {
  24. // certFile and keyFile are set in buildHttpsServer
  25. return svr.ListenAndServeTLS(certFile, keyFile)
  26. }, opts...)
  27. }
  28. func start(host string, port int, handler http.Handler, run func(svr *http.Server) error,
  29. opts ...StartOption) (err error) {
  30. server := &http.Server{
  31. Addr: fmt.Sprintf("%s:%d", host, port),
  32. Handler: handler,
  33. }
  34. for _, opt := range opts {
  35. opt(server)
  36. }
  37. healthManager := health.NewHealthManager(fmt.Sprintf("%s-%s:%d", probeNamePrefix, host, port))
  38. waitForCalled := proc.AddShutdownListener(func() {
  39. healthManager.MarkNotReady()
  40. if e := server.Shutdown(context.Background()); e != nil {
  41. logx.Error(e)
  42. }
  43. })
  44. defer func() {
  45. if errors.Is(err, http.ErrServerClosed) {
  46. waitForCalled()
  47. }
  48. }()
  49. healthManager.MarkReady()
  50. health.AddProbe(healthManager)
  51. return run(server)
  52. }