serve.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package myth
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "syscall"
  10. "time"
  11. //"golang.org/x/net/http2"
  12. )
  13. var (
  14. readTimeout = 30 * time.Second
  15. readHeaderTimeout = 30 * time.Second
  16. writeTimeout = 30 * time.Second
  17. idleTimeout = 30 * time.Second
  18. shutTimeout = 30 * time.Second
  19. )
  20. func newServe(addr string, router http.Handler) *http.Server {
  21. return &http.Server{
  22. Addr: addr,
  23. Handler: router,
  24. ReadTimeout: readTimeout,
  25. ReadHeaderTimeout: readHeaderTimeout,
  26. WriteTimeout: writeTimeout,
  27. IdleTimeout: idleTimeout,
  28. MaxHeaderBytes: MB,
  29. }
  30. }
  31. func run(useV2 bool, addr, certFile, keyFile string, router http.Handler) {
  32. s := newServe(addr, router)
  33. /*
  34. if useV2 {
  35. http2.VerboseLogs = false
  36. http2.ConfigureServer(s, nil)
  37. }
  38. // */
  39. errc := make(chan error)
  40. go func() {
  41. c := make(chan os.Signal, 1)
  42. signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
  43. errc <- fmt.Errorf("%s", <-c)
  44. }()
  45. go func() {
  46. var e error
  47. log.Println("HTTP Server listen on", addr)
  48. if len(certFile) > 0 && len(keyFile) > 0 {
  49. e = s.ListenAndServeTLS(certFile, keyFile)
  50. } else {
  51. e = s.ListenAndServe()
  52. }
  53. log.Println("Exit HTTP server", "Quit", e)
  54. }()
  55. e := <-errc
  56. log.Println("Recvie", e)
  57. ctx, cancel := context.WithTimeout(context.Background(), shutTimeout)
  58. defer cancel()
  59. s.Shutdown(ctx)
  60. log.Println("Exit HTTP server")
  61. }
  62. // ListenAndServe new server and start
  63. func ListenAndServe(addr string, router http.Handler) {
  64. run(false, addr, ``, ``, router)
  65. }
  66. // ListenAndServeTLS new server and start
  67. func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler) {
  68. run(false, addr, certFile, keyFile, router)
  69. }
  70. // ListenAndServeV2 new http2 server and start
  71. func ListenAndServeV2(addr string, router http.Handler) {
  72. run(true, addr, ``, ``, router)
  73. }
  74. // ListenAndServeTLSV2 new http2 server and start
  75. func ListenAndServeTLSV2(addr, certFile, keyFile string, router http.Handler) {
  76. run(true, addr, certFile, keyFile, router)
  77. }