server.go 2.7 KB

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