server.go 4.0 KB

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