starter.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package internal
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "net/http"
  7. "github.com/tal-tech/go-zero/core/proc"
  8. )
  9. func StartHttp(host string, port int, handler http.Handler) error {
  10. addr := fmt.Sprintf("%s:%d", host, port)
  11. server := buildHttpServer(addr, handler)
  12. gracefulOnShutdown(server)
  13. return server.ListenAndServe()
  14. }
  15. func StartHttps(host string, port int, certFile, keyFile string, handler http.Handler) error {
  16. addr := fmt.Sprintf("%s:%d", host, port)
  17. if server, err := buildHttpsServer(addr, handler, certFile, keyFile); err != nil {
  18. return err
  19. } else {
  20. gracefulOnShutdown(server)
  21. // certFile and keyFile are set in buildHttpsServer
  22. return server.ListenAndServeTLS("", "")
  23. }
  24. }
  25. func buildHttpServer(addr string, handler http.Handler) *http.Server {
  26. return &http.Server{Addr: addr, Handler: handler}
  27. }
  28. func buildHttpsServer(addr string, handler http.Handler, certFile, keyFile string) (*http.Server, error) {
  29. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  30. if err != nil {
  31. return nil, err
  32. }
  33. config := tls.Config{Certificates: []tls.Certificate{cert}}
  34. return &http.Server{
  35. Addr: addr,
  36. Handler: handler,
  37. TLSConfig: &config,
  38. }, nil
  39. }
  40. func gracefulOnShutdown(srv *http.Server) {
  41. proc.AddWrapUpListener(func() {
  42. srv.Shutdown(context.Background())
  43. })
  44. }