serve.go 1.8 KB

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