Skip to content

Commit

Permalink
Proxying Accept-Encoding and Accept headers for /asis
Browse files Browse the repository at this point in the history
  • Loading branch information
dooman87 committed Jan 29, 2025
1 parent 2d3b96c commit 705606f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
21 changes: 20 additions & 1 deletion img/loader/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var client = &http.Client{
},
}

func (r *Http) Load(url string, _ context.Context) (*img.Image, error) {
func (r *Http) Load(url string, ctx context.Context) (*img.Image, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
Expand All @@ -44,6 +44,14 @@ func (r *Http) Load(url string, _ context.Context) (*img.Image, error) {
}
}

if moreHeaders, ok := headerFromContext(ctx); ok {
for k, v := range *moreHeaders {
for _, headerVal := range v {
req.Header.Add(k, headerVal)
}
}
}

resp, err := client.Do(req)
if err != nil {
return nil, err
Expand All @@ -70,3 +78,14 @@ func (r *Http) Load(url string, _ context.Context) (*img.Image, error) {
MimeType: contentType,
}, nil
}

type headersKey int

func NewContextWithHeaders(ctx context.Context, headers *http.Header) context.Context {
return context.WithValue(ctx, headersKey(0), headers)
}

func headerFromContext(ctx context.Context) (*http.Header, bool) {
header, ok := ctx.Value(headersKey(0)).(*http.Header)
return header, ok
}
6 changes: 5 additions & 1 deletion img/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"github.com/Pixboost/transformimgs/v8/img/loader"
"github.com/dooman87/glogi"
"github.com/gorilla/mux"
"net/http"
Expand Down Expand Up @@ -192,7 +193,10 @@ func (r *Service) AsIs(resp http.ResponseWriter, req *http.Request) {

Log.Printf("Requested image %s as is\n", imgUrl)

result, err := r.Loader.Load(imgUrl, req.Context())
var proxyHeaders http.Header
proxyHeaders.Add("Accept", req.Header.Get("Accept"))
proxyHeaders.Add("Accept-Encoding", req.Header.Get("Accept-Encoding"))
result, err := r.Loader.Load(imgUrl, loader.NewContextWithHeaders(req.Context(), &proxyHeaders))

if err != nil {
sendError(resp, err)
Expand Down

0 comments on commit 705606f

Please sign in to comment.