serve.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. /*
  28. if useV2 {
  29. http2.VerboseLogs = false
  30. http2.ConfigureServer(s, nil)
  31. }
  32. // */
  33. errc := make(chan error)
  34. go func() {
  35. c := make(chan os.Signal)
  36. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  37. errc <- fmt.Errorf("%s", <-c)
  38. }()
  39. go func() {
  40. log.Println("HTTP Server listen on", addr)
  41. if len(certFile) > 0 && len(keyFile) > 0 {
  42. errc <- s.ListenAndServeTLS(certFile, keyFile)
  43. } else {
  44. errc <- s.ListenAndServe()
  45. }
  46. log.Println("Exit HTTP server", "Quit")
  47. }()
  48. log.Println("Exit", <-errc)
  49. }
  50. // ListenAndServe new server and start
  51. func ListenAndServe(addr string, router http.Handler) {
  52. run(false, addr, ``, ``, router)
  53. }
  54. // ListenAndServeTLS new server and start
  55. func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler) {
  56. run(false, addr, certFile, keyFile, router)
  57. }
  58. // ListenAndServeV2 new http2 server and start
  59. func ListenAndServeV2(addr string, router http.Handler) {
  60. run(true, addr, ``, ``, router)
  61. }
  62. // ListenAndServeTLSV2 new http2 server and start
  63. func ListenAndServeTLSV2(addr, certFile, keyFile string, router http.Handler) {
  64. run(true, addr, certFile, keyFile, router)
  65. }