starter.go 1.6 KB

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