forked from openpitrix/openpitrix
/
local.go
82 lines (73 loc) · 2 KB
/
local.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
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package devkit
import (
"fmt"
"html/template"
"net/http"
"path/filepath"
"strings"
"openpitrix.io/openpitrix/pkg/devkit/opapp"
)
const DefaultServeAddr = "127.0.0.1:9191"
const indexHTMLTemplate = `
<html>
<head>
<title>OpenPitrix Repository</title>
</head>
<h1>OpenPitrix Apps Repository</h1>
<h6>Thanks to <a href="https://helm.sh/">Helm Project</a></h6>
<ul>
{{range $name, $ver := .Index.Entries}}
<li>{{$name}}<ul>{{range $ver}}
<li><a href="{{index .URLs 0}}">{{.Name}}-{{.OpVersion}}</a></li>
{{end}}</ul>
</li>
{{end}}
</ul>
<body>
<p>Last Generated: {{.Index.Generated}}</p>
</body>
</html>
`
// RepositoryServer is an HTTP handler for serving a app repository.
type RepositoryServer struct {
RepoPath string
}
// ServeHTTP implements the http.Handler interface.
func (s *RepositoryServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
uri := r.URL.Path
switch uri {
case "/", "/apps/", "/apps/index.html", "/apps/index":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
s.htmlIndex(w, r)
default:
file := strings.TrimPrefix(uri, "/apps/")
http.ServeFile(w, r, filepath.Join(s.RepoPath, file))
}
}
// StartLocalRepo starts a web server and serves files from the given path
func StartLocalRepo(path, address string) error {
if address == "" {
address = DefaultServeAddr
}
s := &RepositoryServer{RepoPath: path}
return http.ListenAndServe(address, s)
}
func (s *RepositoryServer) htmlIndex(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.New("index.html").Parse(indexHTMLTemplate))
// load index
lrp := filepath.Join(s.RepoPath, "index.yaml")
i, err := opapp.LoadIndexFile(lrp)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
data := map[string]interface{}{
"Index": i,
}
if err := t.Execute(w, data); err != nil {
fmt.Fprintf(w, "Template error: %s", err)
}
}