server.go 4.5 KB

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