support sumdb

pull/136/head
kun 2020-02-18 21:56:04 +08:00
parent fa12c6beba
commit 0aabdb55f7
3 changed files with 84 additions and 0 deletions

View File

@ -16,6 +16,7 @@ import (
"time" "time"
"github.com/goproxyio/goproxy/v2/renameio" "github.com/goproxyio/goproxy/v2/renameio"
"github.com/goproxyio/goproxy/v2/sumdb"
) )
const ListExpire = 5 * time.Minute const ListExpire = 5 * time.Minute
@ -110,6 +111,12 @@ func (rt *Router) Direct(path string) bool {
} }
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// sumdb handler
if strings.HasPrefix(r.URL.Path, "/sumdb/") {
sumdb.Handler(w, r)
return
}
if rt.proxy == nil || rt.Direct(strings.TrimPrefix(r.URL.Path, "/")) { if rt.proxy == nil || rt.Direct(strings.TrimPrefix(r.URL.Path, "/")) {
log.Printf("------ --- %s [direct]\n", r.URL) log.Printf("------ --- %s [direct]\n", r.URL)
rt.srv.ServeHTTP(w, r) rt.srv.ServeHTTP(w, r)

View File

@ -15,6 +15,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/goproxyio/goproxy/v2/sumdb"
"golang.org/x/mod/module" "golang.org/x/mod/module"
) )
@ -119,6 +121,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
} }
// sumdb handler
if strings.HasPrefix(r.URL.Path, "/sumdb/") {
sumdb.Handler(w, r)
return
}
i := strings.Index(r.URL.Path, "/@") i := strings.Index(r.URL.Path, "/@")
if i < 0 { if i < 0 {
http.Error(w, "no such path", http.StatusNotFound) http.Error(w, "no such path", http.StatusNotFound)

68
sumdb/handler.go Normal file
View File

@ -0,0 +1,68 @@
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package proxy implements the HTTP protocols for serving a Go module proxy.
package sumdb
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
var enableGoogleSumDB bool
var supportedSumDB = []string{
"sum.golang.org",
"gosum.io",
}
func init() {
go func() {
p := "https://sum.google.com"
_, err := http.Get(p)
if err == nil {
enableGoogleSumDB = true
}
}()
}
//Handler handles sumdb request
func Handler(w http.ResponseWriter, r *http.Request) {
if !enableGoogleSumDB {
w.WriteHeader(http.StatusNotFound)
return
}
for _, supported := range supportedSumDB {
uri := fmt.Sprintf("/sumdb/%s/supported", supported)
if r.URL.Path == uri {
w.WriteHeader(http.StatusOK)
return
}
}
p := "https://" + strings.TrimPrefix(r.URL.Path, "/sumdb/")
_, err := url.Parse(p)
if err != nil {
w.WriteHeader(http.StatusGone)
fmt.Fprintf(w, err.Error())
return
}
resp, err := http.Get(p)
if err != nil {
w.WriteHeader(http.StatusGone)
fmt.Fprintf(w, err.Error())
return
}
defer resp.Body.Close()
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); err != nil {
fmt.Fprintf(w, err.Error())
return
}
return
}