server.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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/reuseport"
  14. "github.com/imgproxy/imgproxy/v3/router"
  15. )
  16. var (
  17. imgproxyIsRunningMsg = []byte("imgproxy is running")
  18. errInvalidSecret = ierrors.New(403, "Invalid secret", "Forbidden")
  19. )
  20. func buildRouter() *router.Router {
  21. r := router.New(config.PathPrefix)
  22. r.PanicHandler = handlePanic
  23. r.GET("/", handleLanding, true)
  24. r.GET("/health", handleHealth, true)
  25. r.GET("/favicon.ico", handleFavicon, true)
  26. r.GET("/", 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 withCORS(h router.RouteHandler) router.RouteHandler {
  63. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  64. if len(config.AllowOrigin) > 0 {
  65. rw.Header().Set("Access-Control-Allow-Origin", config.AllowOrigin)
  66. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  67. }
  68. h(reqID, rw, r)
  69. }
  70. }
  71. func withSecret(h router.RouteHandler) router.RouteHandler {
  72. if len(config.Secret) == 0 {
  73. return h
  74. }
  75. authHeader := []byte(fmt.Sprintf("Bearer %s", config.Secret))
  76. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  77. if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), authHeader) == 1 {
  78. h(reqID, rw, r)
  79. } else {
  80. panic(errInvalidSecret)
  81. }
  82. }
  83. }
  84. func handlePanic(reqID string, rw http.ResponseWriter, r *http.Request, err error) {
  85. ierr := ierrors.Wrap(err, 3)
  86. if ierr.Unexpected {
  87. errorreport.Report(err, r)
  88. }
  89. router.LogResponse(reqID, r, ierr.StatusCode, ierr)
  90. rw.WriteHeader(ierr.StatusCode)
  91. if config.DevelopmentErrorsMode {
  92. rw.Write([]byte(ierr.Message))
  93. } else {
  94. rw.Write([]byte(ierr.PublicMessage))
  95. }
  96. }
  97. func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
  98. router.LogResponse(reqID, r, 200, nil)
  99. rw.WriteHeader(200)
  100. rw.Write(imgproxyIsRunningMsg)
  101. }
  102. func handleHead(reqID string, rw http.ResponseWriter, r *http.Request) {
  103. router.LogResponse(reqID, r, 200, nil)
  104. rw.WriteHeader(200)
  105. }
  106. func handleFavicon(reqID string, rw http.ResponseWriter, r *http.Request) {
  107. router.LogResponse(reqID, r, 200, nil)
  108. // TODO: Add a real favicon maybe?
  109. rw.WriteHeader(200)
  110. }