server.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. initProcessingHandler()
  35. go func() {
  36. logNotice("Starting server at %s", conf.Bind)
  37. if err := s.Serve(l); err != nil && err != http.ErrServerClosed {
  38. logFatal(err.Error())
  39. }
  40. }()
  41. return s
  42. }
  43. func shutdownServer(s *http.Server) {
  44. logNotice("Shutting down the server...")
  45. ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
  46. defer close()
  47. s.Shutdown(ctx)
  48. }
  49. func withCORS(h routeHandler) routeHandler {
  50. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  51. if len(conf.AllowOrigin) > 0 {
  52. rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
  53. rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  54. }
  55. h(reqID, rw, r)
  56. }
  57. }
  58. func withSecret(h routeHandler) routeHandler {
  59. if len(conf.Secret) == 0 {
  60. return h
  61. }
  62. authHeader := []byte(fmt.Sprintf("Bearer %s", conf.Secret))
  63. return func(reqID string, rw http.ResponseWriter, r *http.Request) {
  64. if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), authHeader) == 1 {
  65. h(reqID, rw, r)
  66. } else {
  67. panic(errInvalidSecret)
  68. }
  69. }
  70. }
  71. func handlePanic(reqID string, rw http.ResponseWriter, r *http.Request, err error) {
  72. reportError(err, r)
  73. var (
  74. ierr *imgproxyError
  75. ok bool
  76. )
  77. if ierr, ok = err.(*imgproxyError); !ok {
  78. ierr = newUnexpectedError(err.Error(), 3)
  79. }
  80. logResponse(reqID, ierr.StatusCode, ierr.Message)
  81. rw.WriteHeader(ierr.StatusCode)
  82. if conf.DevelopmentErrorsMode {
  83. rw.Write([]byte(ierr.Message))
  84. } else {
  85. rw.Write([]byte(ierr.PublicMessage))
  86. }
  87. }
  88. func handleHealth(reqID string, rw http.ResponseWriter, r *http.Request) {
  89. logResponse(reqID, 200, string(imgproxyIsRunningMsg))
  90. rw.WriteHeader(200)
  91. rw.Write(imgproxyIsRunningMsg)
  92. }
  93. func handleOptions(reqID string, rw http.ResponseWriter, r *http.Request) {
  94. logResponse(reqID, 200, "Respond with options")
  95. rw.WriteHeader(200)
  96. }