starter.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. )
  9. // StartOption defines the method to customize http.Server.
  10. type StartOption func(svr *http.Server)
  11. // StartHttp starts a http server.
  12. func StartHttp(host string, port int, handler http.Handler, opts ...StartOption) error {
  13. return start(host, port, handler, func(svr *http.Server) error {
  14. return svr.ListenAndServe()
  15. }, opts...)
  16. }
  17. // StartHttps starts a https server.
  18. func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler,
  19. opts ...StartOption) error {
  20. return start(host, port, handler, func(svr *http.Server) error {
  21. // certFile and keyFile are set in buildHttpsServer
  22. return svr.ListenAndServeTLS(certFile, keyFile)
  23. }, opts...)
  24. }
  25. func start(host string, port int, handler http.Handler, run func(svr *http.Server) error,
  26. opts ...StartOption) (err error) {
  27. server := &http.Server{
  28. Addr: fmt.Sprintf("%s:%d", host, port),
  29. Handler: handler,
  30. }
  31. for _, opt := range opts {
  32. opt(server)
  33. }
  34. waitForCalled := proc.AddWrapUpListener(func() {
  35. if e := server.Shutdown(context.Background()); err != nil {
  36. logx.Error(e)
  37. }
  38. })
  39. defer func() {
  40. if err == http.ErrServerClosed {
  41. waitForCalled()
  42. }
  43. }()
  44. return run(server)
  45. }