serve.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package xhttp
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "syscall"
  9. //"golang.org/x/net/http2"
  10. )
  11. func run(addr string, router http.Handler, option ServerOption) (errs, err error) {
  12. s := &http.Server{
  13. Addr: addr,
  14. Handler: router,
  15. ReadTimeout: option.ReadTimeout,
  16. ReadHeaderTimeout: option.ReadHeaderTimeout,
  17. WriteTimeout: option.WriteTimeout,
  18. IdleTimeout: option.IdleTimeout,
  19. MaxHeaderBytes: option.MaxHeaderBytes,
  20. }
  21. errc := make(chan error)
  22. go func() {
  23. c := make(chan os.Signal, 1)
  24. signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
  25. errc <- fmt.Errorf("%s", <-c)
  26. }()
  27. go func() {
  28. if len(option.CertFile) > 0 && len(option.KeyFile) > 0 {
  29. /*
  30. http2.VerboseLogs = false
  31. http2.ConfigureServer(s, nil)
  32. // */
  33. errs = s.ListenAndServeTLS(option.CertFile, option.KeyFile)
  34. } else {
  35. errs = s.ListenAndServe()
  36. }
  37. errc <- errs
  38. }()
  39. err = <-errc
  40. ctx, cancel := context.WithTimeout(context.Background(), option.ShutdownTimeout)
  41. defer cancel()
  42. s.Shutdown(ctx)
  43. return
  44. }
  45. // ListenAndServe new server and start
  46. func ListenAndServe(addr string, router http.Handler, option ServerOption) (es, e error) {
  47. return run(addr, router, option)
  48. }
  49. // ListenAndServeV2 new http2 server and start
  50. func ListenAndServeV2(addr string, router http.Handler, option ServerOption) (es, e error) {
  51. return run(addr, router, option)
  52. }