add -cache flag and default to no cache

The imageproxy command no longer uses the in-memory cache by default.
Instead, no caching is enabled by default and the in-memory cache can be
enabled by passing `-cache memory`.

The -cache flag also supports specifying directories, and therefore
replaces hte older -cacheDir flag.  cacheDir is still supported for
compatibility, but is deprecated and will be removed in the future.

This also sets us up to add support for additional caching backends in
the future.

Partial fix for #49.
This commit is contained in:
Will Norris 2015-12-04 15:52:40 -08:00
parent 9d4058ca58
commit b88f2b70e5
2 changed files with 50 additions and 18 deletions

View file

@ -43,7 +43,8 @@ var addr = flag.String("addr", "localhost:8080", "TCP address to listen on")
var whitelist = flag.String("whitelist", "", "comma separated list of allowed remote hosts")
var referrers = flag.String("referrers", "", "comma separated list of allowed referring hosts")
var baseURL = flag.String("baseURL", "", "default base URL for relative remote URLs")
var cacheDir = flag.String("cacheDir", "", "directory to use for file cache")
var cache = flag.String("cache", "", "location to cache images (see https://github.com/willnorris/imageproxy#cache)")
var cacheDir = flag.String("cacheDir", "", "(Deprecated; use 'cache' instead) directory to use for file cache")
var cacheSize = flag.Uint64("cacheSize", 100, "maximum size of file cache (in MB)")
var signatureKey = flag.String("signatureKey", "", "HMAC key used in calculating request signatures")
var scaleUp = flag.Bool("scaleUp", false, "allow images to scale beyond their original dimensions")
@ -57,15 +58,9 @@ func main() {
return
}
var c httpcache.Cache
if *cacheDir != "" {
d := diskv.New(diskv.Options{
BasePath: *cacheDir,
CacheSizeMax: *cacheSize * 1024 * 1024,
})
c = diskcache.NewWithDiskv(d)
} else if *cacheSize != 0 {
c = httpcache.NewMemoryCache()
c, err := parseCache()
if err != nil {
log.Fatal(err)
}
p := imageproxy.NewProxy(nil, c)
@ -105,3 +100,37 @@ func main() {
fmt.Printf("imageproxy (version %v) listening on %s\n", VERSION, server.Addr)
log.Fatal(server.ListenAndServe())
}
// parseCache parses the cache-related flags and returns the specified Cache implementation.
func parseCache() (imageproxy.Cache, error) {
if *cache == "" {
if *cacheDir != "" {
return diskCache(*cacheDir), nil
}
return nil, nil
}
if *cache == "memory" {
return httpcache.NewMemoryCache(), nil
}
u, err := url.Parse(*cache)
if err != nil {
return nil, fmt.Errorf("error parsing cache flag: %v", err)
}
switch u.Scheme {
case "file":
fallthrough
default:
return diskCache(u.Path), nil
}
}
func diskCache(path string) *diskcache.Cache {
d := diskv.New(diskv.Options{
BasePath: path,
CacheSizeMax: *cacheSize * 1024 * 1024,
})
return diskcache.NewWithDiskv(d)
}