4
0

server.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. package server
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "log"
  6. "net"
  7. "net/http"
  8. "os"
  9. "time"
  10. "github.com/pkg/errors"
  11. )
  12. // ServerShutdownTimeout is the default time to wait before closing
  13. // connections on shutdown.
  14. const ServerShutdownTimeout = 60 * time.Second
  15. // Server is a incomplete component that implements a basic HTTP/HTTPS
  16. // server.
  17. type Server struct {
  18. *http.Server
  19. listener *net.TCPListener
  20. reloadCh chan net.Listener
  21. shutdownCh chan struct{}
  22. }
  23. // New creates a new HTTP/HTTPS server configured with the passed
  24. // address, http.Handler and tls.Config.
  25. func New(addr string, handler http.Handler, tlsConfig *tls.Config, httpTimeout time.Duration) *Server {
  26. return &Server{
  27. reloadCh: make(chan net.Listener),
  28. shutdownCh: make(chan struct{}),
  29. Server: newHTTPServer(addr, handler, tlsConfig, httpTimeout),
  30. }
  31. }
  32. // newHTTPServer creates a new http.Server with the TCP address, handler and
  33. // tls.Config.
  34. func newHTTPServer(addr string, handler http.Handler, tlsConfig *tls.Config, httpTimeout time.Duration) *http.Server {
  35. return &http.Server{
  36. Addr: addr,
  37. Handler: handler,
  38. TLSConfig: tlsConfig,
  39. WriteTimeout: httpTimeout,
  40. ReadTimeout: httpTimeout,
  41. ReadHeaderTimeout: httpTimeout,
  42. IdleTimeout: httpTimeout,
  43. ErrorLog: log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Llongfile),
  44. }
  45. }
  46. // ListenAndServe listens on the TCP network address srv.Addr and then calls
  47. // Serve to handle requests on incoming connections.
  48. func (srv *Server) ListenAndServe() error {
  49. ln, err := net.Listen("tcp", srv.Addr)
  50. if err != nil {
  51. return err
  52. }
  53. return srv.Serve(ln)
  54. }
  55. // Serve runs Serve or ServeTLS on the underlying http.Server and listen to
  56. // channels to reload or shutdown the server.
  57. func (srv *Server) Serve(ln net.Listener) error {
  58. var err error
  59. // Store the current listener.
  60. // In reloads we'll create a copy of the underlying os.File so the close of the server one does not affect the copy.
  61. srv.listener = ln.(*net.TCPListener)
  62. for {
  63. // Start server
  64. if srv.TLSConfig == nil || (len(srv.TLSConfig.Certificates) == 0 && srv.TLSConfig.GetCertificate == nil) {
  65. log.Printf("Serving HTTP on %s ...", srv.Addr)
  66. err = srv.Server.Serve(ln)
  67. } else {
  68. log.Printf("Serving HTTPS on %s ...", srv.Addr)
  69. err = srv.Server.ServeTLS(ln, "", "")
  70. }
  71. // log unexpected errors
  72. if err != http.ErrServerClosed {
  73. log.Println(errors.Wrap(err, "unexpected error"))
  74. }
  75. select {
  76. case ln = <-srv.reloadCh:
  77. srv.listener = ln.(*net.TCPListener)
  78. case <-srv.shutdownCh:
  79. return http.ErrServerClosed
  80. }
  81. }
  82. }
  83. // Shutdown gracefully shuts down the server without interrupting any active
  84. // connections.
  85. func (srv *Server) Shutdown() error {
  86. ctx, cancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
  87. defer cancel() // release resources if Shutdown ends before the timeout
  88. defer close(srv.shutdownCh) // close shutdown channel
  89. return srv.Server.Shutdown(ctx)
  90. }
  91. func (srv *Server) reloadShutdown() error {
  92. ctx, cancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
  93. defer cancel() // release resources if Shutdown ends before the timeout
  94. return srv.Server.Shutdown(ctx)
  95. }
  96. // Reload reloads the current server with the configuration of the passed
  97. // server.
  98. func (srv *Server) Reload(ns *Server) error {
  99. var err error
  100. var ln net.Listener
  101. if srv.Addr != ns.Addr {
  102. // Open new address
  103. ln, err = net.Listen("tcp", ns.Addr)
  104. if err != nil {
  105. return errors.WithStack(err)
  106. }
  107. } else {
  108. // Get a copy of the underlying os.File
  109. fd, err := srv.listener.File()
  110. if err != nil {
  111. return errors.WithStack(err)
  112. }
  113. // Make sure to close the copy
  114. defer fd.Close()
  115. // Creates a new listener copying fd
  116. ln, err = net.FileListener(fd)
  117. if err != nil {
  118. return errors.WithStack(err)
  119. }
  120. }
  121. // Close old server without sending a signal
  122. if err := srv.reloadShutdown(); err != nil {
  123. return err
  124. }
  125. // Update old server
  126. srv.Server = ns.Server
  127. srv.reloadCh <- ln
  128. return nil
  129. }
  130. // Forbidden writes on the http.ResponseWriter a text/plain forbidden
  131. // response.
  132. func (srv *Server) Forbidden(w http.ResponseWriter) {
  133. header := w.Header()
  134. header.Set("Content-Type", "text/plain; charset=utf-8")
  135. header.Set("Content-Length", "11")
  136. w.WriteHeader(http.StatusForbidden)
  137. w.Write([]byte("Forbidden.\n"))
  138. }