From 0fff9ea92386b58eef2701d2115370aa77f1e5a6 Mon Sep 17 00:00:00 2001 From: Hiroaki Nakamura Date: Fri, 13 Jan 2017 05:52:47 +0900 Subject: [PATCH] Add origin and host flags to the CLI --- cli/httpcache.go | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/cli/httpcache.go b/cli/httpcache.go index cdd96c5..88ef4b3 100644 --- a/cli/httpcache.go +++ b/cli/httpcache.go @@ -5,18 +5,24 @@ import ( "log" "net/http" "net/http/httputil" + "net/url" "os" + "path" + "strings" "github.com/lox/httpcache" "github.com/lox/httpcache/httplog" ) const ( + defaultOrigin = "http://127.0.0.1:80" defaultListen = "0.0.0.0:8080" defaultDir = "./cachedata" ) var ( + origin string + host string listen string useDisk bool private bool @@ -26,6 +32,8 @@ var ( ) func init() { + flag.StringVar(&origin, "origin", defaultOrigin, "the origin url to proxy to") + flag.StringVar(&host, "host", "", "the host header to send") flag.StringVar(&listen, "listen", defaultListen, "the host and port to bind to") flag.StringVar(&dir, "dir", defaultDir, "the dir to store cache data in, implies -disk") flag.BoolVar(&useDisk, "disk", false, "whether to store cache data to disk") @@ -40,10 +48,23 @@ func init() { } func main() { + u, err := url.Parse(origin) + if err != nil { + log.Fatal(err) + } + proxy := &httputil.ReverseProxy{ Director: func(r *http.Request) { - r.URL.Scheme = "http" - r.URL.Host = "127.0.0.1:80" + r.URL.Scheme = u.Scheme + r.URL.Host = u.Host + if strings.HasSuffix(r.URL.Path, "/") { + r.URL.Path = path.Join(u.Path, r.URL.Path) + "/" + } else { + r.URL.Path = path.Join(u.Path, r.URL.Path) + } + if host != "" { + r.Host = host + } }, }