gddo-server: Add a flag to config the address of memcache

Change-Id: Ie55186c0ec8d591e7075fd0c4af7ac819d92b4c4
Reviewed-on: https://go-review.googlesource.com/43453
Reviewed-by: Stephen Weinberg <stephenmw@google.com>
diff --git a/gddo-server/client.go b/gddo-server/client.go
index 07966f8..14b65a3 100644
--- a/gddo-server/client.go
+++ b/gddo-server/client.go
@@ -10,10 +10,8 @@
 package main
 
 import (
-	"fmt"
 	"net"
 	"net/http"
-	"os"
 
 	"github.com/gregjones/httpcache"
 	"github.com/gregjones/httpcache/memcache"
@@ -23,10 +21,8 @@
 )
 
 func newHTTPClient() *http.Client {
-	t := newCacheTransport()
-
 	requestTimeout := viper.GetDuration(ConfigRequestTimeout)
-	t.Transport = &http.Transport{
+	t := &http.Transport{
 		Proxy: http.ProxyFromEnvironment,
 		Dial: (&net.Dialer{
 			Timeout:   viper.GetDuration(ConfigDialTimeout),
@@ -35,26 +31,18 @@
 		ResponseHeaderTimeout: requestTimeout / 2,
 		TLSHandshakeTimeout:   requestTimeout / 2,
 	}
+
+	var rt http.RoundTripper
+	if addr := viper.GetString(ConfigMemcacheAddr); addr != "" {
+		ct := httpcache.NewTransport(memcache.New(addr))
+		ct.Transport = t
+		rt = httputil.NewAuthTransport(ct)
+	} else {
+		rt = httputil.NewAuthTransport(t)
+	}
 	return &http.Client{
 		// Wrap the cached transport with GitHub authentication.
-		Transport: httputil.NewAuthTransport(t),
+		Transport: rt,
 		Timeout:   requestTimeout,
 	}
 }
-
-func newCacheTransport() *httpcache.Transport {
-	// host and port are set by GAE Flex runtime, can be left blank locally.
-	host := os.Getenv("MEMCACHE_PORT_11211_TCP_ADDR")
-	if host == "" {
-		host = "localhost"
-	}
-	port := os.Getenv("MEMCACHE_PORT_11211_TCP_PORT")
-	if port == "" {
-		port = "11211"
-	}
-	addr := fmt.Sprintf("%s:%s", host, port)
-
-	return httpcache.NewTransport(
-		memcache.New(addr),
-	)
-}
diff --git a/gddo-server/config.go b/gddo-server/config.go
index be929df..372e2b3 100644
--- a/gddo-server/config.go
+++ b/gddo-server/config.go
@@ -43,6 +43,7 @@
 	ConfigCrawlInterval   = "crawl_interval"
 	ConfigDialTimeout     = "dial_timeout"
 	ConfigRequestTimeout  = "request_timeout"
+	ConfigMemcacheAddr    = "memcache_addr"
 )
 
 // Initialize configuration
@@ -100,6 +101,7 @@
 	flags.String(ConfigDBServer, "redis://127.0.0.1:6379", "URI of Redis server.")
 	flags.Duration(ConfigDBIdleTimeout, 250*time.Second, "Close Redis connections after remaining idle for this duration.")
 	flags.Bool(ConfigDBLog, false, "Log database commands")
+	flags.String(ConfigMemcacheAddr, "", "Address in the format host:port gddo uses to point to the memcache backend.")
 
 	return flags
 }