-
Notifications
You must be signed in to change notification settings - Fork 2
/
proxy.go
73 lines (61 loc) · 1.8 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"golang.org/x/net/html"
)
func proxyRepo(ctx context.Context, dep string) (string, error) {
url := fmt.Sprintf("https://%s?go-get=1", dep)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("GET %q - %w", url, err)
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GET %q - %s", url, resp.Status)
}
defer resp.Body.Close()
return parseProxyHTML(resp.Body)
}
/*
Looking for go-source in HTML
<html>
<head>
<meta name="go-import" content="gopkg.in/yaml.v3 git https://gopkg.in/yaml.v3">
<meta name="go-source" content="gopkg.in/yaml.v3 _ https://github.com/go-yaml/yaml/tree/v3.0.1{/dir} https://github.com/go-yaml/yaml/blob/v3.0.1{/dir}/{file}#L{line}">
</head>
<body>
go get gopkg.in/yaml.v3
</body>
</html>
*/
// gopkg.in/yaml.v3 _ https://github.com/go-yaml/yaml/tree/v3.0.1{/dir} https://github.com/go-yaml/yaml/blob/v3.0.1{/dir}/{file}#L{line} -> https://github.com/go-yaml/yaml
var ghRE = regexp.MustCompile(`https://(github.com/[^/]+/[^/ ]+)`)
// parseProxyHTML finds github repo in proxy HTML.
func parseProxyHTML(r io.Reader) (string, error) {
doc, err := html.Parse(r)
if err != nil {
return "", err
}
pred := func(n *html.Node) bool { return n.Data == "meta" && attr(n, "name") == "go-source" }
node := findNode(doc, pred)
if node == nil {
return "", fmt.Errorf("can't find go-source meta")
}
src := attr(node, "content")
if src == "" {
return "", fmt.Errorf("can't find content in meta")
}
matches := ghRE.FindStringSubmatch(src)
if len(matches) == 0 {
return "", fmt.Errorf("can't find github repo in meta")
}
return strings.TrimSpace(matches[1]), nil
}