forked from zikes/gopkg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgopkg.go
123 lines (100 loc) · 2.07 KB
/
gopkg.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Usage:
//
// gopkg [path] [vcs-type] [uri]
// gopkg [path] [uri]
package gopkg
import (
"html/template"
"net/http"
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
func init() {
caddy.RegisterPlugin("gopkg", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
type Config struct {
Path string
Vcs string
Uri string
}
type GopkgHandler struct {
Next httpserver.Handler
Configs []Config
}
var tmpl = template.Must(template.New("").Parse(`<html>
<head>
<meta name="go-import" content="{{.Host}}{{.Path}} {{.Vcs}} {{.Uri}}">
</head>
<body>
go get {{.Host}}{{.Path}}
</body>
</html>
`))
func (g GopkgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
for i := range g.Configs {
// Check if the request path should be handled by Gopkg middleware
if !httpserver.Path(r.URL.Path).Matches(g.Configs[i].Path) {
continue
}
cfg := &g.Configs[i]
// Check if the request path contains go-get=1
if r.FormValue("go-get") != "1" {
http.Redirect(w, r, cfg.Uri, http.StatusTemporaryRedirect)
return 0, nil
}
host := r.Host
err := tmpl.Execute(w, struct {
Host string
Path string
Vcs string
Uri string
}{
Host: host,
Path: cfg.Path,
Vcs: cfg.Vcs,
Uri: cfg.Uri,
})
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
return g.Next.ServeHTTP(w, r)
}
func setup(c *caddy.Controller) error {
configs, err := parse(c)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
return GopkgHandler{
Configs: configs,
Next: next,
}
})
return nil
}
func parse(c *caddy.Controller) ([]Config, error) {
var configs []Config
for c.Next() {
args := c.RemainingArgs()
if len(args) != 2 && len(args) != 3 {
return configs, c.ArgErr()
}
cfg := Config{
Vcs: "git",
Path: args[0],
}
if len(args) == 2 {
cfg.Uri = args[1]
} else {
cfg.Vcs = args[1]
cfg.Uri = args[2]
}
configs = append(configs, cfg)
}
return configs, nil
}