server.go 3.2 KB

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