serve.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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)
  42. signal.Notify(c, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
  43. errc <- fmt.Errorf("%s", <-c)
  44. }()
  45. go func() {
  46. log.Println("HTTP Server listen on", addr)
  47. if len(certFile) > 0 && len(keyFile) > 0 {
  48. errc <- s.ListenAndServeTLS(certFile, keyFile)
  49. } else {
  50. errc <- s.ListenAndServe()
  51. }
  52. //log.Println("Exit HTTP server", "Quit")
  53. }()
  54. e := <-errc
  55. log.Println("Recvie", e)
  56. ctx, cancel := context.WithTimeout(context.Background(), shutTimeout)
  57. defer cancel()
  58. s.Shutdown(ctx)
  59. log.Println("Exit HTTP server")
  60. }
  61. // ListenAndServe new server and start
  62. func ListenAndServe(addr string, router http.Handler) {
  63. run(false, addr, ``, ``, router)
  64. }
  65. // ListenAndServeTLS new server and start
  66. func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler) {
  67. run(false, addr, certFile, keyFile, router)
  68. }
  69. // ListenAndServeV2 new http2 server and start
  70. func ListenAndServeV2(addr string, router http.Handler) {
  71. run(true, addr, ``, ``, router)
  72. }
  73. // ListenAndServeTLSV2 new http2 server and start
  74. func ListenAndServeTLSV2(addr, certFile, keyFile string, router http.Handler) {
  75. run(true, addr, certFile, keyFile, router)
  76. }