server.go 4.3 KB

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