server.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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()
  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.OPTIONS("/", withCORS(handleOptions), false)
  22. return r
  23. }
  24. func startServer() *http.Server {
  25. l, err := listenReuseport("tcp", conf.Bind)
  26. if err != nil {
  27. logFatal(err.Error())
  28. }
  29. l = netutil.LimitListener(l, conf.MaxClients)
  30. s := &http.Server{
  31. Handler: buildRouter(),
  32. ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
  33. MaxHeaderBytes: 1 << 20,
  34. }
  35. if conf.KeepAliveTimeout > 0 {
  36. s.IdleTimeout = time.Duration(conf.KeepAliveTimeout) * time.Second
  37. } else {
  38. s.SetKeepAlivesEnabled(false)
  39. }
  40. initProcessingHandler()
  41. go func() {
  42. logNotice("Starting server at %s", conf.Bind)
  43. if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
  44. logFatal(err.Error())
  45. }
  46. }()
  47. return s
  48. }
  49. func shutdownServer(s *http.Server) {
  50. logNotice("Shutting down the server...")
  51. ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
  52. defer close()
  53. s.Shutdown(ctx)
  54. }
  55. func withCORS(h routeHandler) routeHandler {
  56. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  57. if len(conf.AllowOrigin) > 0 {
  58. rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
  59. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  60. }
  61. h(reqID, rw, r)
  62. }
  63. }
  64. func withSecret(h routeHandler) routeHandler {
  65. if len(conf.Secret) == 0 {
  66. return h
  67. }
  68. authHeader := []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  69. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  70. if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), authHeader) == 1 {
  71. h(reqID, rw, r)
  72. } else {
  73. panic(errInvalidSecret)
  74. }
  75. }
  76. }
  77. func handlePanic(reqID string, rw http.ResponseWriter, r *http.Request, err error) {
  78. var (
  79. ierr *imgproxyError
  80. ok bool
  81. )
  82. if ierr, ok = err.(*imgproxyError); !ok {
  83. ierr = newUnexpectedError(err.Error(), 3)
  84. }
  85. if ierr.Unexpected {
  86. reportError(err, r)
  87. }
  88. logResponse(reqID, r, ierr.StatusCode, ierr, nil, nil)
  89. rw.WriteHeader(ierr.StatusCode)
  90. if conf.DevelopmentErrorsMode {
  91. rw.Write([]byte(ierr.Message))
  92. } else {
  93. rw.Write([]byte(ierr.PublicMessage))
  94. }
  95. }
  96. func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
  97. logResponse(reqID, r, 200, nil, nil, nil)
  98. rw.WriteHeader(200)
  99. rw.Write(imgproxyIsRunningMsg)
  100. }
  101. func handleOptions(reqID string, rw http.ResponseWriter, r *http.Request) {
  102. logResponse(reqID, r, 200, nil, nil, nil)
  103. rw.WriteHeader(200)
  104. }
  105. func handleFavicon(reqID string, rw http.ResponseWriter, r *http.Request) {
  106. logResponse(reqID, r, 200, nil, nil, nil)
  107. // TODO: Add a real favicon maybe?
  108. rw.WriteHeader(200)
  109. }