Browse Source

Add UserAgent and DownloadTimeout to imagefetcher config

DarthSim 1 month ago
parent
commit
5bbdc37cea
2 changed files with 17 additions and 5 deletions
  1. 15 2
      imagefetcher/config.go
  2. 2 3
      imagefetcher/fetcher.go

+ 15 - 2
imagefetcher/config.go

@@ -1,9 +1,18 @@
 package imagefetcher
 
-import "github.com/imgproxy/imgproxy/v3/config"
+import (
+	"time"
+
+	"github.com/imgproxy/imgproxy/v3/config"
+	"github.com/imgproxy/imgproxy/v3/version"
+)
 
 // Config holds the configuration for the image fetcher.
 type Config struct {
+	// UserAgent is the User-Agent header to use when fetching images.
+	UserAgent string
+	// DownloadTimeout is the timeout for downloading an image, in seconds.
+	DownloadTimeout time.Duration
 	// MaxRedirects is the maximum number of redirects to follow when fetching an image.
 	MaxRedirects int
 }
@@ -11,12 +20,16 @@ type Config struct {
 // NewDefaultConfig returns a new Config instance with default values.
 func NewDefaultConfig() *Config {
 	return &Config{
-		MaxRedirects: 10,
+		UserAgent:       "imgproxy/" + version.Version,
+		DownloadTimeout: 5 * time.Second,
+		MaxRedirects:    10,
 	}
 }
 
 // LoadFromEnv loads config variables from env
 func (c *Config) LoadFromEnv() (*Config, error) {
+	c.UserAgent = config.UserAgent
+	c.DownloadTimeout = time.Duration(config.DownloadTimeout) * time.Second
 	c.MaxRedirects = config.MaxRedirects
 	return c, nil
 }

+ 2 - 3
imagefetcher/fetcher.go

@@ -7,7 +7,6 @@ import (
 	"net/http"
 	"time"
 
-	"github.com/imgproxy/imgproxy/v3/config"
 	"github.com/imgproxy/imgproxy/v3/httpheaders"
 	"github.com/imgproxy/imgproxy/v3/transport"
 	"github.com/imgproxy/imgproxy/v3/transport/common"
@@ -55,7 +54,7 @@ func (f *Fetcher) BuildRequest(ctx context.Context, url string, header http.Head
 	url = common.EscapeURL(url)
 
 	// Set request timeout and get cancel function
-	ctx, cancel := context.WithTimeout(ctx, time.Duration(config.DownloadTimeout)*time.Second)
+	ctx, cancel := context.WithTimeout(ctx, f.config.DownloadTimeout)
 
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
 	if err != nil {
@@ -77,7 +76,7 @@ func (f *Fetcher) BuildRequest(ctx context.Context, url string, header http.Head
 	}
 
 	// Set user agent header
-	req.Header.Set(httpheaders.UserAgent, config.UserAgent)
+	req.Header.Set(httpheaders.UserAgent, f.config.UserAgent)
 
 	// Set headers
 	httpheaders.CopyToRequest(header, req)