浏览代码

Unify HTTP handler definitions

DarthSim 3 周之前
父节点
当前提交
adb4341713
共有 7 个文件被更改,包括 120 次插入65 次删除
  1. 26 19
      config.go
  2. 16 4
      handlers/health/handler.go
  3. 5 2
      handlers/health/handler_test.go
  4. 0 9
      handlers/landing/body.html
  5. 31 0
      handlers/landing/handler.go
  6. 41 30
      imgproxy.go
  7. 1 1
      integration/processing_handler_test.go

+ 26 - 19
config.go

@@ -5,35 +5,42 @@ import (
 	"github.com/imgproxy/imgproxy/v3/ensure"
 	"github.com/imgproxy/imgproxy/v3/fetcher"
 	processinghandler "github.com/imgproxy/imgproxy/v3/handlers/processing"
-	"github.com/imgproxy/imgproxy/v3/handlers/stream"
+	streamhandler "github.com/imgproxy/imgproxy/v3/handlers/stream"
 	"github.com/imgproxy/imgproxy/v3/headerwriter"
 	"github.com/imgproxy/imgproxy/v3/semaphores"
 	"github.com/imgproxy/imgproxy/v3/server"
 )
 
+// HandlerConfigs holds the configurations for imgproxy handlers
+type HandlerConfigs struct {
+	Processing processinghandler.Config
+	Stream     streamhandler.Config
+}
+
 // Config represents an instance configuration
 type Config struct {
-	HeaderWriter      headerwriter.Config
-	Semaphores        semaphores.Config
-	FallbackImage     auximageprovider.StaticConfig
-	WatermarkImage    auximageprovider.StaticConfig
-	Fetcher           fetcher.Config
-	ProcessingHandler processinghandler.Config
-	StreamHandler     stream.Config
-	Server            server.Config
+	HeaderWriter   headerwriter.Config
+	Semaphores     semaphores.Config
+	FallbackImage  auximageprovider.StaticConfig
+	WatermarkImage auximageprovider.StaticConfig
+	Fetcher        fetcher.Config
+	Handlers       HandlerConfigs
+	Server         server.Config
 }
 
 // NewDefaultConfig creates a new default configuration
 func NewDefaultConfig() Config {
 	return Config{
-		HeaderWriter:      headerwriter.NewDefaultConfig(),
-		Semaphores:        semaphores.NewDefaultConfig(),
-		FallbackImage:     auximageprovider.NewDefaultStaticConfig(),
-		WatermarkImage:    auximageprovider.NewDefaultStaticConfig(),
-		Fetcher:           fetcher.NewDefaultConfig(),
-		ProcessingHandler: processinghandler.NewDefaultConfig(),
-		StreamHandler:     stream.NewDefaultConfig(),
-		Server:            server.NewDefaultConfig(),
+		HeaderWriter:   headerwriter.NewDefaultConfig(),
+		Semaphores:     semaphores.NewDefaultConfig(),
+		FallbackImage:  auximageprovider.NewDefaultStaticConfig(),
+		WatermarkImage: auximageprovider.NewDefaultStaticConfig(),
+		Fetcher:        fetcher.NewDefaultConfig(),
+		Handlers: HandlerConfigs{
+			Processing: processinghandler.NewDefaultConfig(),
+			Stream:     streamhandler.NewDefaultConfig(),
+		},
+		Server: server.NewDefaultConfig(),
 	}
 }
 
@@ -67,11 +74,11 @@ func LoadConfigFromEnv(c *Config) (*Config, error) {
 		return nil, err
 	}
 
-	if _, err = processinghandler.LoadConfigFromEnv(&c.ProcessingHandler); err != nil {
+	if _, err = processinghandler.LoadConfigFromEnv(&c.Handlers.Processing); err != nil {
 		return nil, err
 	}
 
-	if _, err = stream.LoadConfigFromEnv(&c.StreamHandler); err != nil {
+	if _, err = streamhandler.LoadConfigFromEnv(&c.Handlers.Stream); err != nil {
 		return nil, err
 	}
 

+ 16 - 4
handlers/health.go → handlers/health/handler.go

@@ -1,4 +1,4 @@
-package handlers
+package health
 
 import (
 	"net/http"
@@ -11,8 +11,20 @@ import (
 
 var imgproxyIsRunningMsg = []byte("imgproxy is running")
 
-// HealthHandler handles the health check requests
-func HealthHandler(reqID string, rw http.ResponseWriter, r *http.Request) error {
+// Handler handles health requests
+type Handler struct{}
+
+// New creates new handler object
+func New() *Handler {
+	return &Handler{}
+}
+
+// Execute handles the health request
+func (h *Handler) Execute(
+	reqID string,
+	rw http.ResponseWriter,
+	req *http.Request,
+) error {
 	var (
 		status int
 		msg    []byte
@@ -34,7 +46,7 @@ func HealthHandler(reqID string, rw http.ResponseWriter, r *http.Request) error
 
 	// Log response only if something went wrong
 	if ierr != nil {
-		server.LogResponse(reqID, r, status, ierr)
+		server.LogResponse(reqID, req, status, ierr)
 	}
 
 	rw.Header().Set(httpheaders.ContentType, "text/plain")

+ 5 - 2
handlers/health_test.go → handlers/health/handler_test.go

@@ -1,4 +1,4 @@
-package handlers
+package health
 
 import (
 	"net/http"
@@ -14,8 +14,11 @@ func TestHealthHandler(t *testing.T) {
 	// Create a ResponseRecorder to record the response
 	rr := httptest.NewRecorder()
 
+	// Create a new health handler
+	h := New()
+
 	// Call the handler function directly (no need for actual HTTP request)
-	HealthHandler("test-req-id", rr, nil)
+	h.Execute("test-req-id", rr, nil)
 
 	// Check that we get a valid response (either 200 or 500 depending on vips state)
 	assert.True(t, rr.Code == http.StatusOK || rr.Code == http.StatusInternalServerError)

文件差异内容过多而无法显示
+ 0 - 9
handlers/landing/body.html


+ 31 - 0
handlers/landing/handler.go

@@ -0,0 +1,31 @@
+package landing
+
+import (
+	_ "embed"
+	"net/http"
+
+	"github.com/imgproxy/imgproxy/v3/httpheaders"
+)
+
+//go:embed body.html
+var landingBody []byte
+
+// Handler handles landing requests
+type Handler struct{}
+
+// New creates new handler object
+func New() *Handler {
+	return &Handler{}
+}
+
+// Execute handles the landing request
+func (h *Handler) Execute(
+	reqID string,
+	rw http.ResponseWriter,
+	req *http.Request,
+) error {
+	rw.Header().Set(httpheaders.ContentType, "text/html")
+	rw.WriteHeader(http.StatusOK)
+	rw.Write(landingBody)
+	return nil
+}

+ 41 - 30
imgproxy.go

@@ -7,9 +7,10 @@ import (
 
 	"github.com/imgproxy/imgproxy/v3/auximageprovider"
 	"github.com/imgproxy/imgproxy/v3/fetcher"
-	"github.com/imgproxy/imgproxy/v3/handlers"
+	healthhandler "github.com/imgproxy/imgproxy/v3/handlers/health"
+	landinghandler "github.com/imgproxy/imgproxy/v3/handlers/landing"
 	processinghandler "github.com/imgproxy/imgproxy/v3/handlers/processing"
-	"github.com/imgproxy/imgproxy/v3/handlers/stream"
+	streamhandler "github.com/imgproxy/imgproxy/v3/handlers/stream"
 	"github.com/imgproxy/imgproxy/v3/headerwriter"
 	"github.com/imgproxy/imgproxy/v3/imagedata"
 	"github.com/imgproxy/imgproxy/v3/memory"
@@ -23,17 +24,24 @@ const (
 	healthPath  = "/health"
 )
 
+// ImgproxyHandlers holds the handlers for imgproxy
+type ImgproxyHandlers struct {
+	Health     *healthhandler.Handler
+	Landing    *landinghandler.Handler
+	Processing *processinghandler.Handler
+	Stream     *streamhandler.Handler
+}
+
 // Imgproxy holds all the components needed for imgproxy to function
 type Imgproxy struct {
-	HeaderWriter      *headerwriter.Writer
-	Semaphores        *semaphores.Semaphores
-	FallbackImage     auximageprovider.Provider
-	WatermarkImage    auximageprovider.Provider
-	Fetcher           *fetcher.Fetcher
-	ProcessingHandler *processinghandler.Handler
-	StreamHandler     *stream.Handler
-	ImageDataFactory  *imagedata.Factory
-	Config            *Config
+	HeaderWriter     *headerwriter.Writer
+	Semaphores       *semaphores.Semaphores
+	FallbackImage    auximageprovider.Provider
+	WatermarkImage   auximageprovider.Provider
+	Fetcher          *fetcher.Fetcher
+	ImageDataFactory *imagedata.Factory
+	Handlers         ImgproxyHandlers
+	Config           *Config
 }
 
 // New creates a new imgproxy instance
@@ -65,29 +73,32 @@ func New(ctx context.Context, config *Config) (*Imgproxy, error) {
 		return nil, err
 	}
 
-	streamHandler, err := stream.New(&config.StreamHandler, headerWriter, fetcher)
+	imgproxy := &Imgproxy{
+		HeaderWriter:     headerWriter,
+		Semaphores:       semaphores,
+		FallbackImage:    fallbackImage,
+		WatermarkImage:   watermarkImage,
+		Fetcher:          fetcher,
+		ImageDataFactory: idf,
+		Config:           config,
+	}
+
+	imgproxy.Handlers.Health = healthhandler.New()
+	imgproxy.Handlers.Landing = landinghandler.New()
+
+	imgproxy.Handlers.Stream, err = streamhandler.New(&config.Handlers.Stream, headerWriter, fetcher)
 	if err != nil {
 		return nil, err
 	}
 
-	ph, err := processinghandler.New(
-		streamHandler, headerWriter, semaphores, fallbackImage, watermarkImage, idf, &config.ProcessingHandler,
+	imgproxy.Handlers.Processing, err = processinghandler.New(
+		imgproxy.Handlers.Stream, headerWriter, semaphores, fallbackImage, watermarkImage, idf, &config.Handlers.Processing,
 	)
 	if err != nil {
 		return nil, err
 	}
 
-	return &Imgproxy{
-		HeaderWriter:      headerWriter,
-		Semaphores:        semaphores,
-		FallbackImage:     fallbackImage,
-		WatermarkImage:    watermarkImage,
-		Fetcher:           fetcher,
-		StreamHandler:     streamHandler,
-		ProcessingHandler: ph,
-		ImageDataFactory:  idf,
-		Config:            config,
-	}, nil
+	return imgproxy, nil
 }
 
 // BuildRouter sets up the HTTP routes and middleware
@@ -97,17 +108,17 @@ func (i *Imgproxy) BuildRouter() (*server.Router, error) {
 		return nil, err
 	}
 
-	r.GET("/", handlers.LandingHandler)
-	r.GET("", handlers.LandingHandler)
+	r.GET("/", i.Handlers.Landing.Execute)
+	r.GET("", i.Handlers.Landing.Execute)
 
 	r.GET(faviconPath, r.NotFoundHandler).Silent()
-	r.GET(healthPath, handlers.HealthHandler).Silent()
+	r.GET(healthPath, i.Handlers.Health.Execute).Silent()
 	if i.Config.Server.HealthCheckPath != "" {
-		r.GET(i.Config.Server.HealthCheckPath, handlers.HealthHandler).Silent()
+		r.GET(i.Config.Server.HealthCheckPath, i.Handlers.Health.Execute).Silent()
 	}
 
 	r.GET(
-		"/*", i.ProcessingHandler.Execute,
+		"/*", i.Handlers.Processing.Execute,
 		r.WithSecret, r.WithCORS, r.WithPanic, r.WithReportError, r.WithMonitoring,
 	)
 

+ 1 - 1
integration/processing_handler_test.go

@@ -426,7 +426,7 @@ func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareMoreRecentLastMo
 }
 
 func (s *ProcessingHandlerTestSuite) TestModifiedSinceReqCompareTooOldLastModifiedDisabled() {
-	s.Config().ProcessingHandler.LastModifiedEnabled = false
+	s.Config().Handlers.Processing.LastModifiedEnabled = false
 	data := s.TestData.Read("test1.png")
 	ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
 		modifiedSince := r.Header.Get(httpheaders.IfModifiedSince)

部分文件因为文件数量过多而无法显示