serve.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package myth
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "syscall"
  9. "time"
  10. )
  11. func newServe(addr string, router http.Handler) *http.Server {
  12. return &http.Server{
  13. Addr: addr,
  14. Handler: router,
  15. ReadTimeout: 30 * time.Second,
  16. WriteTimeout: 30 * time.Second,
  17. MaxHeaderBytes: 1 << 20,
  18. }
  19. }
  20. // ListenAndServe new server and start
  21. func ListenAndServe(addr string, router http.Handler) {
  22. s := newServe(addr, router)
  23. errc := make(chan error)
  24. go func() {
  25. c := make(chan os.Signal)
  26. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  27. errc <- fmt.Errorf("%s", <-c)
  28. }()
  29. go func() {
  30. log.Println("HTTP Server listen on", addr)
  31. errc <- s.ListenAndServe()
  32. log.Println("Exit HTTP server", "Quit")
  33. }()
  34. log.Println("Exit", <-errc)
  35. }
  36. // ListenAndServeTLS new server and start
  37. func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler) {
  38. s := newServe(addr, router)
  39. errc := make(chan error)
  40. go func() {
  41. c := make(chan os.Signal)
  42. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  43. errc <- fmt.Errorf("%s", <-c)
  44. }()
  45. go func() {
  46. log.Println("HTTP Server listen on", addr)
  47. errc <- s.ListenAndServeTLS(certFile, keyFile)
  48. log.Println("Exit HTTP server", "Quit")
  49. }()
  50. log.Println("Exit", <-errc)
  51. }