Go code updates

Former-commit-id: ac2160fe6ef9c41c7b180a8af967f3d44f126394 [formerly c99451b289742e4738812c3f4bcfdc63931f2e6a] [formerly 10bc4c44b68391f2be0ee965187caaaaa27ba8f0 [formerly 1a4242ca06a3fa7ede2942364c9854ef3bfb39f1]]
Former-commit-id: b3555e3ea88e695ee72a87cee4b226f3d0a1d48d [formerly 70e58315f9e2a3bb3e46d48b3280127aa49107c5]
Former-commit-id: d66ddf727e7924b95e2caf88f3c02de17a1f86cf
This commit is contained in:
Henrique Dias
2017-07-08 17:51:47 +01:00
parent f6aeb27ca4
commit b4067cc423
8 changed files with 728 additions and 599 deletions

67
http.go
View File

@@ -53,7 +53,7 @@ func serveHTTP(c *requestContext, w http.ResponseWriter, r *http.Request) (int,
// API handler if so.
if matchURL(r.URL.Path, "/api") {
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/api")
return serveAPI(c, w, r)
return apiHandler(c, w, r)
}
// Any other request should show the index.html file.
@@ -84,6 +84,54 @@ func staticHandler(c *requestContext, w http.ResponseWriter, r *http.Request) (i
)
}
// apiHandler is the main entry point for the /api endpoint.
func apiHandler(c *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
if r.URL.Path == "/auth/get" {
return authHandler(c, w, r)
}
if r.URL.Path == "/auth/renew" {
return renewAuthHandler(c, w, r)
}
valid, _ := validateAuth(c, r)
if !valid {
return http.StatusForbidden, nil
}
var router string
router, r.URL.Path = cleanURL(r.URL.Path)
if !c.us.Allowed(r.URL.Path) {
return http.StatusForbidden, nil
}
if router == "checksum" || router == "download" {
var err error
c.fi, err = getInfo(r.URL, c.fm, c.us)
if err != nil {
return errorToHTTP(err, false), err
}
}
switch router {
case "download":
return downloadHandler(c, w, r)
case "checksum":
return checksumHandler(c, w, r)
case "command":
return command(c, w, r)
case "search":
return search(c, w, r)
case "resource":
return resourceHandler(c, w, r)
case "users":
return usersHandler(c, w, r)
}
return http.StatusNotFound, nil
}
// serveChecksum calculates the hash of a file. Supports MD5, SHA1, SHA256 and SHA512.
func checksumHandler(c *requestContext, w http.ResponseWriter, r *http.Request) (int, error) {
query := r.URL.Query().Get("algo")
@@ -99,6 +147,23 @@ func checksumHandler(c *requestContext, w http.ResponseWriter, r *http.Request)
return 0, nil
}
// cleanURL splits the path and returns everything that stands
// before the first slash and everything that goes after.
func cleanURL(path string) (string, string) {
if path == "" {
return "", ""
}
path = strings.TrimPrefix(path, "/")
i := strings.Index(path, "/")
if i == -1 {
return "", path
}
return path[0:i], path[i:len(path)]
}
// renderFile renders a file using a template with some needed variables.
func renderFile(w http.ResponseWriter, file string, contentType string, baseURL string) (int, error) {
tpl := template.Must(template.New("file").Parse(file))