serve.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. )
  12. var (
  13. readTimeout = 30 * time.Second
  14. writeTimeout = 30 * time.Second
  15. )
  16. func newServe(addr string, router http.Handler) *http.Server {
  17. return &http.Server{
  18. Addr: addr,
  19. Handler: router,
  20. ReadTimeout: readTimeout,
  21. WriteTimeout: writeTimeout,
  22. MaxHeaderBytes: MB,
  23. }
  24. }
  25. func run(useV2 bool, addr, certFile, keyFile string, router http.Handler) {
  26. s := newServe(addr, router)
  27. if useV2 {
  28. http2.VerboseLogs = false
  29. http2.ConfigureServer(s, nil)
  30. }
  31. errc := make(chan error)
  32. go func() {
  33. c := make(chan os.Signal)
  34. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  35. errc <- fmt.Errorf("%s", <-c)
  36. }()
  37. go func() {
  38. log.Println("HTTP Server listen on", addr)
  39. if len(certFile) > 0 && len(keyFile) > 0 {
  40. errc <- s.ListenAndServeTLS(certFile, keyFile)
  41. } else {
  42. errc <- s.ListenAndServe()
  43. }
  44. log.Println("Exit HTTP server", "Quit")
  45. }()
  46. log.Println("Exit", <-errc)
  47. }
  48. // ListenAndServe new server and start
  49. func ListenAndServe(addr string, router http.Handler) {
  50. run(false, addr, ``, ``, router)
  51. }
  52. // ListenAndServeTLS new server and start
  53. func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler) {
  54. run(false, addr, certFile, keyFile, router)
  55. }
  56. // ListenAndServeV2 new http2 server and start
  57. func ListenAndServeV2(addr string, router http.Handler) {
  58. run(true, addr, ``, ``, router)
  59. }
  60. // ListenAndServeTLSV2 new http2 server and start
  61. func ListenAndServeTLSV2(addr, certFile, keyFile string, router http.Handler) {
  62. run(true, addr, certFile, keyFile, router)
  63. }