From 530b0e308e3416cb97f0e085d08217fbbdd87428 Mon Sep 17 00:00:00 2001 From: Y4ssss Date: Thu, 28 Oct 2021 09:54:47 +0800 Subject: [PATCH] feat: support to set cache expiration --- main.go | 8 ++++---- proxy/router.go | 5 ++++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 5fb1552..0703ebb 100644 --- a/main.go +++ b/main.go @@ -40,19 +40,18 @@ import ( ) var downloadRoot string - -const listExpire = proxy.ListExpire - var listen, promListen string var cacheDir string var proxyHost string var excludeHost string +var cacheExpire time.Duration func init() { flag.StringVar(&excludeHost, "exclude", "", "exclude host pattern, you can exclude internal Git services") flag.StringVar(&proxyHost, "proxy", "", "next hop proxy for Go Modules, recommend use https://gopropxy.io") flag.StringVar(&cacheDir, "cacheDir", "", "Go Modules cache dir, default is $GOPATH/pkg/mod/cache/download") flag.StringVar(&listen, "listen", "0.0.0.0:8081", "service listen address") + flag.DurationVar(&cacheExpire, "cacheExpire", 5*time.Minute, "Go Modules cache expiration (min), default is 5 min") flag.Parse() if os.Getenv("GIT_TERMINAL_PROMPT") == "" { @@ -89,6 +88,7 @@ func main() { Pattern: excludeHost, Proxy: proxyHost, DownloadRoot: downloadRoot, + CacheExpire: cacheExpire, })} } else { handle = &logger{proxy.NewServer(new(ops))} @@ -195,7 +195,7 @@ func (*ops) List(ctx context.Context, mpath string) (proxy.File, error) { return nil, err } file := filepath.Join(downloadRoot, escMod, "@v", "list") - if info, err := os.Stat(file); err == nil && time.Since(info.ModTime()) < listExpire { + if info, err := os.Stat(file); err == nil && time.Since(info.ModTime()) < cacheExpire { return os.Open(file) } var list struct { diff --git a/proxy/router.go b/proxy/router.go index ffbc0d8..88920b5 100644 --- a/proxy/router.go +++ b/proxy/router.go @@ -30,6 +30,7 @@ type RouterOptions struct { Pattern string Proxy string DownloadRoot string + CacheExpire time.Duration } // A Router is the proxy HTTP server, @@ -41,6 +42,7 @@ type Router struct { proxy *httputil.ReverseProxy pattern string downloadRoot string + cacheExpire time.Duration } func (router *Router) customModResponse(r *http.Response) error { @@ -157,6 +159,7 @@ func NewRouter(srv *Server, opts *RouterOptions) *Router { rt.proxy.ModifyResponse = rt.customModResponse rt.pattern = opts.Pattern rt.downloadRoot = opts.DownloadRoot + rt.cacheExpire = opts.CacheExpire } return rt } @@ -215,7 +218,7 @@ func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { what := r.URL.Path[i+len("/@v/"):] if what == "list" { - if time.Since(info.ModTime()) >= ListExpire { + if time.Since(info.ModTime()) >= rt.cacheExpire { log.Printf("------ --- %s [proxy]\n", r.URL) rt.proxy.ServeHTTP(mw, r) totalRequest.With(prometheus.Labels{"mode": "proxy", "status": mw.status()}).Inc()