starter.go 945 B

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