MCPcopy
hub / github.com/willnorris/imageproxy / serveImage

Method serveImage

imageproxy.go:227–346  ·  view source on GitHub ↗

serveImage handles incoming requests for proxied images.

(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

225
226// serveImage handles incoming requests for proxied images.
227func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
228 req, err := NewRequest(r, p.DefaultBaseURL)
229 if err != nil {
230 msg := fmt.Sprintf("invalid request URL: %v", err)
231 p.log(msg)
232 http.Error(w, msg, http.StatusBadRequest)
233 return
234 }
235
236 if err := p.allowed(req); err != nil {
237 p.logf("%s: %v", err, req)
238 http.Error(w, msgNotAllowed, http.StatusForbidden)
239 return
240 }
241
242 // assign static settings from proxy to req.Options
243 req.Options.ScaleUp = p.ScaleUp
244
245 actualReq, _ := http.NewRequest("GET", req.String(), nil)
246 if p.UserAgent != "" {
247 actualReq.Header.Set("User-Agent", p.UserAgent)
248 }
249 if len(p.ContentTypes) != 0 {
250 actualReq.Header.Set("Accept", strings.Join(p.ContentTypes, ", "))
251 }
252 if p.IncludeReferer {
253 // pass along the referer header from the original request
254 copyHeader(actualReq.Header, r.Header, "referer")
255 }
256 if len(p.PassRequestHeaders) != 0 {
257 copyHeader(actualReq.Header, r.Header, p.PassRequestHeaders...)
258 }
259 if p.FollowRedirects {
260 // FollowRedirects is true (default), ensure that the redirected host is allowed
261 p.Client.CheckRedirect = func(newreq *http.Request, via []*http.Request) error {
262 if len(via) > maxRedirects {
263 if p.Verbose {
264 p.logf("followed too many redirects (%d).", len(via))
265 }
266 return errTooManyRedirects
267 }
268 if hostMatches(p.DenyHosts, newreq.URL) {
269 http.Error(w, msgNotAllowedInRedirect, http.StatusForbidden)
270 return errNotAllowed
271 }
272 return nil
273 }
274 } else {
275 // FollowRedirects is false, don't follow redirects
276 p.Client.CheckRedirect = func(newreq *http.Request, via []*http.Request) error {
277 return http.ErrUseLastResponse
278 }
279 }
280 resp, err := p.Client.Do(actualReq)
281
282 if err != nil {
283 msg := fmt.Sprintf("error fetching remote image: %v", err)
284 p.log(msg)

Callers

nothing calls this directly

Calls 15

logMethod · 0.95
allowedMethod · 0.95
logfMethod · 0.95
StringMethod · 0.95
NewRequestFunction · 0.85
copyHeaderFunction · 0.85
hostMatchesFunction · 0.85
should304Function · 0.85
peekContentTypeFunction · 0.85
contentTypeMatchesFunction · 0.85
ErrorMethod · 0.80
HeaderMethod · 0.80

Tested by

no test coverage detected