0
Fork 0
mirror of https://github.com/willnorris/imageproxy.git synced 2024-12-16 21:56:43 -05:00
imageproxy/imageproxy.go

221 lines
6 KiB
Go
Raw Normal View History

// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package imageproxy provides an image proxy server. For typical use of
// creating and using a Proxy, see cmd/imageproxy/main.go.
package imageproxy // import "willnorris.com/go/imageproxy"
2013-11-27 14:02:21 -05:00
import (
2013-12-26 21:31:20 -05:00
"bufio"
"bytes"
2013-11-27 14:02:21 -05:00
"fmt"
2013-12-26 21:31:20 -05:00
"io"
"io/ioutil"
2013-11-27 14:02:21 -05:00
"net/http"
"net/url"
2013-12-26 22:36:18 -05:00
"strings"
"time"
"github.com/golang/glog"
2013-12-25 21:48:10 -05:00
"github.com/gregjones/httpcache"
2013-11-27 14:02:21 -05:00
)
// Proxy serves image requests.
//
// Note that a Proxy should not be run behind a http.ServeMux, since the
// ServeMux aggressively cleans URLs and removes the double slash in the
// embedded request URL.
type Proxy struct {
Client *http.Client // client used to fetch remote URLs
Cache Cache // cache used to cache responses
2013-12-04 06:12:56 -05:00
// Whitelist specifies a list of remote hosts that images can be
// proxied from. An empty list means all hosts are allowed.
2013-12-04 06:12:56 -05:00
Whitelist []string
}
// NewProxy constructs a new proxy. The provided http RoundTripper will be
// used to fetch remote URLs. If nil is provided, http.DefaultTransport will
// be used.
2013-12-26 21:31:20 -05:00
func NewProxy(transport http.RoundTripper, cache Cache) *Proxy {
if transport == nil {
transport = http.DefaultTransport
}
2013-12-25 21:48:10 -05:00
if cache == nil {
cache = NopCache
}
2013-12-26 21:31:20 -05:00
client := new(http.Client)
client.Transport = &httpcache.Transport{
Transport: &TransformingTransport{transport, client},
Cache: cache,
MarkCachedResponses: true,
}
2013-12-25 21:48:10 -05:00
return &Proxy{
2013-12-26 21:31:20 -05:00
Client: client,
Cache: cache,
2013-12-25 21:48:10 -05:00
}
}
// ServeHTTP handles image requests.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2014-11-23 19:04:53 -05:00
if r.URL.Path == "/favicon.ico" {
return // ignore favicon requests
}
req, err := NewRequest(r)
if err != nil {
msg := fmt.Sprintf("invalid request URL: %v", err)
glog.Error(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
2013-12-04 06:12:56 -05:00
if !p.allowed(req.URL) {
msg := fmt.Sprintf("remote URL is not for an allowed host: %v", req.URL)
glog.Error(msg)
http.Error(w, msg, http.StatusBadRequest)
2013-12-04 06:12:56 -05:00
return
}
2013-12-26 21:31:20 -05:00
u := req.URL.String()
if req.Options != emptyOptions {
2013-12-26 21:31:20 -05:00
u += "#" + req.Options.String()
}
resp, err := p.Client.Get(u)
2013-12-25 21:48:10 -05:00
if err != nil {
msg := fmt.Sprintf("error fetching remote image: %v", err)
glog.Error(msg)
http.Error(w, msg, http.StatusInternalServerError)
2013-12-25 21:48:10 -05:00
return
}
if resp.StatusCode != http.StatusOK {
msg := fmt.Sprintf("remote URL %q returned status: %v", req.URL, resp.Status)
glog.Error(msg)
http.Error(w, msg, resp.StatusCode)
2013-12-26 21:31:20 -05:00
return
}
w.Header().Add("Last-Modified", resp.Header.Get("Last-Modified"))
2013-12-26 21:31:20 -05:00
w.Header().Add("Expires", resp.Header.Get("Expires"))
w.Header().Add("Etag", resp.Header.Get("Etag"))
if is304 := check304(r, resp); is304 {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Add("Content-Length", resp.Header.Get("Content-Length"))
2013-12-26 21:31:20 -05:00
defer resp.Body.Close()
io.Copy(w, resp.Body)
}
2013-12-04 06:12:56 -05:00
// allowed returns whether the specified URL is on the whitelist of remote hosts.
func (p *Proxy) allowed(u *url.URL) bool {
if len(p.Whitelist) == 0 {
return true
}
for _, host := range p.Whitelist {
if u.Host == host {
return true
}
2013-12-26 22:36:18 -05:00
if strings.HasPrefix(host, "*.") && strings.HasSuffix(u.Host, host[2:]) {
return true
}
2013-12-04 06:12:56 -05:00
}
return false
}
// check304 checks whether we should send a 304 Not Modified in response to
// req, based on the response resp. This is determined using the last modified
// time and the entity tag of resp.
func check304(req *http.Request, resp *http.Response) bool {
// TODO(willnorris): if-none-match header can be a comma separated list
// of multiple tags to be matched, or the special value "*" which
// matches all etags
etag := resp.Header.Get("Etag")
if etag != "" && etag == req.Header.Get("If-None-Match") {
return true
}
lastModified, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
if err != nil {
return false
}
ifModSince, err := time.Parse(time.RFC1123, req.Header.Get("If-Modified-Since"))
if err != nil {
return false
}
if lastModified.Before(ifModSince) {
return true
}
return false
}
2013-12-26 21:31:20 -05:00
// TransformingTransport is an implementation of http.RoundTripper that
// optionally transforms images using the options specified in the request URL
// fragment.
type TransformingTransport struct {
// Transport is the underlying http.RoundTripper used to satisfy
// non-transform requests (those that do not include a URL fragment).
2013-12-26 21:31:20 -05:00
Transport http.RoundTripper
// CachingClient is used to fetch images to be resized. This client is
// used rather than Transport directly in order to ensure that
// responses are properly cached.
CachingClient *http.Client
2013-12-26 21:31:20 -05:00
}
// RoundTrip implements the http.RoundTripper interface.
2013-12-26 21:31:20 -05:00
func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL.Fragment == "" {
// normal requests pass through
glog.Infof("fetching remote URL: %v", req.URL)
return t.Transport.RoundTrip(req)
}
2013-12-26 21:31:20 -05:00
u := *req.URL
u.Fragment = ""
resp, err := t.CachingClient.Get(u.String())
if err != nil {
return nil, err
}
2013-12-26 21:31:20 -05:00
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
2013-12-26 21:31:20 -05:00
return nil, err
}
2013-12-26 21:31:20 -05:00
opt := ParseOptions(req.URL.Fragment)
img, err := Transform(b, opt)
if err != nil {
img = b
}
// replay response with transformed image and updated content length
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%s %s\n", resp.Proto, resp.Status)
resp.Header.WriteSubset(buf, map[string]bool{"Content-Length": true})
fmt.Fprintf(buf, "Content-Length: %d\n\n", len(img))
buf.Write(img)
return http.ReadResponse(bufio.NewReader(buf), req)
}