starter.go 876 B

1234567891011121314151617181920212223242526272829303132333435
  1. package internal
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "github.com/tal-tech/go-zero/core/proc"
  7. )
  8. func StartHttp(host string, port int, handler http.Handler) error {
  9. return start(host, port, handler, func(srv *http.Server) error {
  10. return srv.ListenAndServe()
  11. })
  12. }
  13. func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error {
  14. return start(host, port, handler, func(srv *http.Server) error {
  15. // certFile and keyFile are set in buildHttpsServer
  16. return srv.ListenAndServeTLS(certFile, keyFile)
  17. })
  18. }
  19. func start(host string, port int, handler http.Handler, run func(srv *http.Server) error) error {
  20. server := &http.Server{
  21. Addr: fmt.Sprintf("%s:%d", host, port),
  22. Handler: handler,
  23. }
  24. waitForCalled := proc.AddWrapUpListener(func() {
  25. server.Shutdown(context.Background())
  26. })
  27. defer waitForCalled()
  28. return run(server)
  29. }