clear code: get path suffix

pull/9/head
ianwoolf 2018-09-06 09:19:18 +08:00 committed by kun
parent 90c421639b
commit 39b23e3b6c
2 changed files with 18 additions and 9 deletions

20
main.go
View File

@ -35,21 +35,20 @@ func main() {
} }
} }
func getPathSuffix(path string) string {
suffixIndex := strings.LastIndex(path, ".")
return path[suffixIndex:]
}
func mainHandler(inner http.Handler) http.Handler { func mainHandler(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(os.Stdout, "goproxy: %s download %s\n", r.RemoteAddr, r.URL.Path) fmt.Fprintf(os.Stdout, "goproxy: %s download %s\n", r.RemoteAddr, r.URL.Path)
if _, err := os.Stat(filepath.Join(cacheDir, r.URL.Path)); err != nil { if _, err := os.Stat(filepath.Join(cacheDir, r.URL.Path)); err != nil {
if strings.HasSuffix(r.URL.Path, ".info") || strings.HasSuffix(r.URL.Path, ".mod") || strings.HasSuffix(r.URL.Path, ".zip") { suffix := getPathSuffix(r.URL.Path)
suffix := ".mod" if suffix == ".info" || suffix == ".mod" || suffix == ".zip" {
if strings.HasSuffix(r.URL.Path, ".info") {
suffix = ".info"
}
if strings.HasSuffix(r.URL.Path, ".zip") {
suffix = ".zip"
}
mod := strings.Split(r.URL.Path, "/@v/") mod := strings.Split(r.URL.Path, "/@v/")
if len(mod) != 2 { if len(mod) != 2 {
ReturnServerError(w, fmt.Errorf("bad module path:%s", r.URL.Path)) ReturnBadRequest(w, fmt.Errorf("bad module path:%s", r.URL.Path))
return return
} }
version := strings.TrimSuffix(mod[1], suffix) version := strings.TrimSuffix(mod[1], suffix)
@ -67,6 +66,9 @@ func mainHandler(inner http.Handler) http.Handler {
// ignore the error, incorrect tag may be given // ignore the error, incorrect tag may be given
// forward to inner.ServeHTTP // forward to inner.ServeHTTP
goGet(path, version, suffix, w, r) goGet(path, version, suffix, w, r)
} else {
ReturnBadRequest(w, fmt.Errorf("bad module path:%s", r.URL.Path))
return
} }
if strings.HasSuffix(r.URL.Path, "/@v/list") { if strings.HasSuffix(r.URL.Path, "/@v/list") {
w.Write([]byte("")) w.Write([]byte(""))

View File

@ -12,3 +12,10 @@ func ReturnServerError(w http.ResponseWriter, err error) {
fmt.Fprintf(os.Stderr, "goproxy: %s\n", msg) fmt.Fprintf(os.Stderr, "goproxy: %s\n", msg)
w.Write([]byte(msg)) w.Write([]byte(msg))
} }
func ReturnBadRequest(w http.ResponseWriter, err error) {
w.WriteHeader(400)
msg := fmt.Sprintf("%v", err)
fmt.Fprintf(os.Stderr, "goproxy: %s\n", msg)
w.Write([]byte(msg))
}