server.go 3.0 KB

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