server.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package main
  2. import (
  3. "context"
  4. "crypto/subtle"
  5. "fmt"
  6. "net/http"
  7. "time"
  8. log "github.com/sirupsen/logrus"
  9. "golang.org/x/net/netutil"
  10. "github.com/imgproxy/imgproxy/v3/config"
  11. "github.com/imgproxy/imgproxy/v3/errorreport"
  12. "github.com/imgproxy/imgproxy/v3/ierrors"
  13. "github.com/imgproxy/imgproxy/v3/metrics"
  14. "github.com/imgproxy/imgproxy/v3/reuseport"
  15. "github.com/imgproxy/imgproxy/v3/router"
  16. )
  17. var (
  18. imgproxyIsRunningMsg = []byte("imgproxy is running")
  19. errInvalidSecret = ierrors.New(403, "Invalid secret", "Forbidden")
  20. )
  21. func buildRouter() *router.Router {
  22. r := router.New(config.PathPrefix)
  23. r.GET("/", handleLanding, true)
  24. r.GET("/health", handleHealth, true)
  25. r.GET("/favicon.ico", handleFavicon, true)
  26. r.GET("/", withMetrics(withPanicHandler(withCORS(withSecret(handleProcessing)))), false)
  27. r.HEAD("/", withCORS(handleHead), false)
  28. r.OPTIONS("/", withCORS(handleHead), false)
  29. return r
  30. }
  31. func startServer(cancel context.CancelFunc) (*http.Server, error) {
  32. l, err := reuseport.Listen(config.Network, config.Bind)
  33. if err != nil {
  34. return nil, fmt.Errorf("Can't start server: %s", err)
  35. }
  36. l = netutil.LimitListener(l, config.MaxClients)
  37. s := &http.Server{
  38. Handler: buildRouter(),
  39. ReadTimeout: time.Duration(config.ReadTimeout) * time.Second,
  40. MaxHeaderBytes: 1 << 20,
  41. }
  42. if config.KeepAliveTimeout > 0 {
  43. s.IdleTimeout = time.Duration(config.KeepAliveTimeout) * time.Second
  44. } else {
  45. s.SetKeepAlivesEnabled(false)
  46. }
  47. go func() {
  48. log.Infof("Starting server at %s", config.Bind)
  49. if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
  50. log.Error(err)
  51. }
  52. cancel()
  53. }()
  54. return s, nil
  55. }
  56. func shutdownServer(s *http.Server) {
  57. log.Info("Shutting down the server...")
  58. ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
  59. defer close()
  60. s.Shutdown(ctx)
  61. }
  62. func withMetrics(h router.RouteHandler) router.RouteHandler {
  63. if !metrics.Enabled() {
  64. return h
  65. }
  66. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  67. ctx, metricsCancel, rw := metrics.StartRequest(r.Context(), rw, r)
  68. defer metricsCancel()
  69. h(reqID, rw, r.WithContext(ctx))
  70. }
  71. }
  72. func withCORS(h router.RouteHandler) router.RouteHandler {
  73. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  74. if len(config.AllowOrigin) > 0 {
  75. rw.Header().Set("Access-Control-Allow-Origin", config.AllowOrigin)
  76. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  77. }
  78. h(reqID, rw, r)
  79. }
  80. }
  81. func withSecret(h router.RouteHandler) router.RouteHandler {
  82. if len(config.Secret) == 0 {
  83. return h
  84. }
  85. authHeader := []byte(fmt.Sprintf("Bearer %s", config.Secret))
  86. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  87. if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), authHeader) == 1 {
  88. h(reqID, rw, r)
  89. } else {
  90. panic(errInvalidSecret)
  91. }
  92. }
  93. }
  94. func withPanicHandler(h router.RouteHandler) router.RouteHandler {
  95. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  96. defer func() {
  97. if rerr := recover(); rerr != nil {
  98. err, ok := rerr.(error)
  99. if !ok {
  100. panic(rerr)
  101. }
  102. ierr := ierrors.Wrap(err, 3)
  103. if ierr.Unexpected {
  104. errorreport.Report(err, r)
  105. }
  106. router.LogResponse(reqID, r, ierr.StatusCode, ierr)
  107. rw.WriteHeader(ierr.StatusCode)
  108. if config.DevelopmentErrorsMode {
  109. rw.Write([]byte(ierr.Message))
  110. } else {
  111. rw.Write([]byte(ierr.PublicMessage))
  112. }
  113. }
  114. }()
  115. h(reqID, rw, r)
  116. }
  117. }
  118. func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
  119. router.LogResponse(reqID, r, 200, nil)
  120. rw.WriteHeader(200)
  121. rw.Write(imgproxyIsRunningMsg)
  122. }
  123. func handleHead(reqID string, rw http.ResponseWriter, r *http.Request) {
  124. router.LogResponse(reqID, r, 200, nil)
  125. rw.WriteHeader(200)
  126. }
  127. func handleFavicon(reqID string, rw http.ResponseWriter, r *http.Request) {
  128. router.LogResponse(reqID, r, 200, nil)
  129. // TODO: Add a real favicon maybe?
  130. rw.WriteHeader(200)
  131. }