forked from elastic/package-registry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
80 lines (67 loc) · 2.13 KB
/
handler.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package main
import (
"errors"
"fmt"
"net/http"
"path/filepath"
"time"
)
func notFoundError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusNotFound)
}
func badRequest(w http.ResponseWriter, errorMessage string) {
http.Error(w, errorMessage, http.StatusBadRequest)
}
func catchAll(public http.FileSystem, cacheTime time.Duration) func(w http.ResponseWriter, r *http.Request) {
fileServer := http.FileServer(public)
return func(w http.ResponseWriter, r *http.Request) {
path, err := determineResourcePath(r, public)
if err != nil {
notFoundError(w, err)
return
}
cacheHeaders(w, cacheTime)
r.URL.Path = path
fileServer.ServeHTTP(w, r)
}
}
func determineResourcePath(r *http.Request, public http.FileSystem) (string, error) {
path := r.URL.Path
// Handles if it's a directory or last char is a / (also a directory)
// It then opens index.json by default (if it exists)
if len(path) == 0 || path == "/" {
path = "index.json"
} else if path[len(path)-1:] == "/" {
path = filepath.Join(path, "index.json")
} else {
f, err := public.Open(path)
if err != nil { // catch all errors, including "forbidden access"
return "", errors.New("404 Page Not Found Error")
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return "", errors.New("404 Page Not Found Error")
}
if stat.IsDir() {
path = path + "/index.json"
dirIndexFile, err := public.Open(path)
if err != nil { // catch all errors, including "forbidden access"
return "", errors.New("404 Page Not Found Error")
}
defer dirIndexFile.Close()
}
}
return path, nil
}
func cacheHeaders(w http.ResponseWriter, cacheTime time.Duration) {
maxAge := fmt.Sprintf("max-age=%.0f", cacheTime.Seconds())
w.Header().Add("Cache-Control", maxAge)
w.Header().Add("Cache-Control", "public")
}
func jsonHeader(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
}