server.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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.ReadTimeout) * 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. defer func() {
  108. if rerr := recover(); rerr != nil {
  109. if rerr == http.ErrAbortHandler {
  110. panic(rerr)
  111. }
  112. err, ok := rerr.(error)
  113. if !ok {
  114. panic(rerr)
  115. }
  116. ierr := ierrors.Wrap(err, 2)
  117. if ierr.Unexpected {
  118. errorreport.Report(err, r)
  119. }
  120. router.LogResponse(reqID, r, ierr.StatusCode, ierr)
  121. rw.Header().Set("Content-Type", "text/plain")
  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. if len(msg) == 0 {
  148. msg = []byte{' '}
  149. }
  150. // Log response only if something went wrong
  151. if ierr != nil {
  152. router.LogResponse(reqID, r, status, ierr)
  153. }
  154. rw.Header().Set("Content-Type", "text/plain")
  155. rw.Header().Set("Cache-Control", "no-cache")
  156. rw.WriteHeader(status)
  157. rw.Write(msg)
  158. }
  159. func handleHead(reqID string, rw http.ResponseWriter, r *http.Request) {
  160. router.LogResponse(reqID, r, 200, nil)
  161. rw.WriteHeader(200)
  162. }