Skip to content

Commit

Permalink
fix: support cache 302 status code
Browse files Browse the repository at this point in the history
  • Loading branch information
pingtest authored and oiooj committed Aug 31, 2020
1 parent 2c71c26 commit a4e417a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func init() {
os.Setenv("GOSUMDB", "off")

downloadRoot = getDownloadRoot()
os.Setenv("GOMODCACHE", downloadRoot)
}

func main() {
Expand Down
48 changes: 48 additions & 0 deletions proxy/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"compress/gzip"
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net/http"
Expand Down Expand Up @@ -96,6 +97,53 @@ func NewRouter(srv *Server, opts *RouterOptions) *Router {
}
}
}

// support 302 status code.
if r.StatusCode == http.StatusFound {
loc := r.Header.Get("Location")
if loc == "" {
return fmt.Errorf("%d response missing Location header", r.StatusCode)
}

// TODO: location is relative.
_, err := url.Parse(loc)
if err != nil {
return fmt.Errorf("failed to parse Location header %q: %v", loc, err)
}
resp, err := http.Get(loc)
if err != nil {
return err
}
defer resp.Body.Close()

var buf []byte
if strings.Contains(resp.Header.Get("Content-Encoding"), "gzip") {
gr, err := gzip.NewReader(resp.Body)
if err != nil {
return err
}
defer gr.Close()
buf, err = ioutil.ReadAll(gr)
if err != nil {
return err
}
resp.Header.Del("Content-Encoding")
} else {
buf, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
}
resp.Body = ioutil.NopCloser(bytes.NewReader(buf))
if buf != nil {
file := filepath.Join(opts.DownloadRoot, r.Request.URL.Path)
os.MkdirAll(path.Dir(file), os.ModePerm)
err = renameio.WriteFile(file, buf, 0666)
if err != nil {
return err
}
}
}
return nil
}
rt.pattern = opts.Pattern
Expand Down

0 comments on commit a4e417a

Please sign in to comment.