server.go 4.6 KB

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