server.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package main
  2. import (
  3. "context"
  4. "crypto/subtle"
  5. "fmt"
  6. golog "log"
  7. "net/http"
  8. "time"
  9. log "github.com/sirupsen/logrus"
  10. "golang.org/x/net/netutil"
  11. "github.com/imgproxy/imgproxy/v3/config"
  12. "github.com/imgproxy/imgproxy/v3/errorreport"
  13. "github.com/imgproxy/imgproxy/v3/ierrors"
  14. "github.com/imgproxy/imgproxy/v3/metrics"
  15. "github.com/imgproxy/imgproxy/v3/reuseport"
  16. "github.com/imgproxy/imgproxy/v3/router"
  17. "github.com/imgproxy/imgproxy/v3/vips"
  18. )
  19. var (
  20. imgproxyIsRunningMsg = []byte("imgproxy is running")
  21. errInvalidSecret = ierrors.New(403, "Invalid secret", "Forbidden")
  22. )
  23. func buildRouter() *router.Router {
  24. r := router.New(config.PathPrefix)
  25. r.GET("/", handleLanding, true)
  26. r.GET("", handleLanding, true)
  27. r.GET("/", withMetrics(withPanicHandler(withCORS(withSecret(handleProcessing)))), false)
  28. r.HEAD("/", withCORS(handleHead), false)
  29. r.OPTIONS("/", withCORS(handleHead), false)
  30. r.HealthHandler = handleHealth
  31. return r
  32. }
  33. func startServer(cancel context.CancelFunc) (*http.Server, error) {
  34. l, err := reuseport.Listen(config.Network, config.Bind)
  35. if err != nil {
  36. return nil, fmt.Errorf("Can't start server: %s", err)
  37. }
  38. if config.MaxClients > 0 {
  39. l = netutil.LimitListener(l, config.MaxClients)
  40. }
  41. errLogger := golog.New(
  42. log.WithField("source", "http_server").WriterLevel(log.ErrorLevel),
  43. "", 0,
  44. )
  45. s := &http.Server{
  46. Handler: buildRouter(),
  47. ReadTimeout: time.Duration(config.ReadRequestTimeout) * time.Second,
  48. MaxHeaderBytes: 1 << 20,
  49. ErrorLog: errLogger,
  50. }
  51. if config.KeepAliveTimeout > 0 {
  52. s.IdleTimeout = time.Duration(config.KeepAliveTimeout) * time.Second
  53. } else {
  54. s.SetKeepAlivesEnabled(false)
  55. }
  56. go func() {
  57. log.Infof("Starting server at %s", config.Bind)
  58. if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
  59. log.Error(err)
  60. }
  61. cancel()
  62. }()
  63. return s, nil
  64. }
  65. func shutdownServer(s *http.Server) {
  66. log.Info("Shutting down the server...")
  67. ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
  68. defer close()
  69. s.Shutdown(ctx)
  70. }
  71. func withMetrics(h router.RouteHandler) router.RouteHandler {
  72. if !metrics.Enabled() {
  73. return h
  74. }
  75. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  76. ctx, metricsCancel, rw := metrics.StartRequest(r.Context(), rw, r)
  77. defer metricsCancel()
  78. h(reqID, rw, r.WithContext(ctx))
  79. }
  80. }
  81. func withCORS(h router.RouteHandler) router.RouteHandler {
  82. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  83. if len(config.AllowOrigin) > 0 {
  84. rw.Header().Set("Access-Control-Allow-Origin", config.AllowOrigin)
  85. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  86. }
  87. h(reqID, rw, r)
  88. }
  89. }
  90. func withSecret(h router.RouteHandler) router.RouteHandler {
  91. if len(config.Secret) == 0 {
  92. return h
  93. }
  94. authHeader := []byte(fmt.Sprintf("Bearer %s", config.Secret))
  95. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  96. if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), authHeader) == 1 {
  97. h(reqID, rw, r)
  98. } else {
  99. panic(errInvalidSecret)
  100. }
  101. }
  102. }
  103. func withPanicHandler(h router.RouteHandler) router.RouteHandler {
  104. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  105. ctx := errorreport.StartRequest(r)
  106. r = r.WithContext(ctx)
  107. errorreport.SetMetadata(r, "Request ID", reqID)
  108. defer func() {
  109. if rerr := recover(); rerr != nil {
  110. if rerr == http.ErrAbortHandler {
  111. panic(rerr)
  112. }
  113. err, ok := rerr.(error)
  114. if !ok {
  115. panic(rerr)
  116. }
  117. ierr := ierrors.Wrap(err, 2)
  118. if ierr.Unexpected {
  119. errorreport.Report(err, r)
  120. }
  121. router.LogResponse(reqID, r, ierr.StatusCode, ierr)
  122. rw.Header().Set("Content-Type", "text/plain")
  123. rw.WriteHeader(ierr.StatusCode)
  124. if config.DevelopmentErrorsMode {
  125. rw.Write([]byte(ierr.Message))
  126. } else {
  127. rw.Write([]byte(ierr.PublicMessage))
  128. }
  129. }
  130. }()
  131. h(reqID, rw, r)
  132. }
  133. }
  134. func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
  135. var (
  136. status int
  137. msg []byte
  138. ierr *ierrors.Error
  139. )
  140. if err := vips.Health(); err == nil {
  141. status = http.StatusOK
  142. msg = imgproxyIsRunningMsg
  143. } else {
  144. status = http.StatusInternalServerError
  145. msg = []byte("Error")
  146. ierr = ierrors.Wrap(err, 1)
  147. }
  148. if len(msg) == 0 {
  149. msg = []byte{' '}
  150. }
  151. // Log response only if something went wrong
  152. if ierr != nil {
  153. router.LogResponse(reqID, r, status, ierr)
  154. }
  155. rw.Header().Set("Content-Type", "text/plain")
  156. rw.Header().Set("Cache-Control", "no-cache")
  157. rw.WriteHeader(status)
  158. rw.Write(msg)
  159. }
  160. func handleHead(reqID string, rw http.ResponseWriter, r *http.Request) {
  161. router.LogResponse(reqID, r, 200, nil)
  162. rw.WriteHeader(200)
  163. }