This repository has been archived by the owner on Jul 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.go
99 lines (82 loc) · 2.46 KB
/
routes.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
package web
import (
"fmt"
"net/http"
"os"
"path"
"path/filepath"
"strings"
log "github.com/sirupsen/logrus"
"github.com/calvinverse/service.provisioning/internal/config"
"github.com/calvinverse/service.provisioning/internal/router"
"github.com/go-chi/chi"
)
// NewWebRouter returns a new router.WebRouter instance
func NewWebRouter(config config.Configuration) router.WebRouter {
return &webRouter{
cfg: config,
}
}
type webRouter struct {
cfg config.Configuration
}
// Routes exports the web routes
func (w *webRouter) Routes(r *chi.Mux, rootRouter func() chi.Router) {
filesDir := ""
if w.cfg.IsSet("ui.path") {
filesDir = w.cfg.GetString("ui.path")
if _, err := os.Stat(filesDir); os.IsNotExist(err) {
panic(
fmt.Sprintf(
"UI directory does not exist.Configuration was set to: %s",
filesDir))
}
} else {
ex, err := os.Executable()
if err != nil {
log.Fatal(
fmt.Sprintf(
"Failed to locate the directory of the executable. Error was: %v",
err))
}
workDir := filepath.Dir(ex)
filesDir = filepath.Join(workDir, "client")
}
log.Debug(
fmt.Sprintf(
"Using UI directory %s",
filesDir))
// Load the index.html
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filesDir+"/index.html")
})
r.Get("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filesDir+"/favicon.ico")
})
w.fileServer(r, "/css", filesDir+"/css")
w.fileServer(r, "/img", filesDir+"/img")
w.fileServer(r, "/js", filesDir+"/js")
w.fileServer(r, "/", filesDir)
}
func (w *webRouter) fileServer(r chi.Router, urlPath string, basePath string) {
if strings.ContainsAny(urlPath, "{}*") {
panic("FileServer does not permit any URL parameters")
}
root, _ := filepath.Abs(basePath)
if _, err := os.Stat(root); os.IsNotExist(err) {
panic("Static Documents Directory Not Found")
}
fs := http.StripPrefix(urlPath, http.FileServer(http.Dir(root)))
if urlPath != "/" && urlPath[len(urlPath)-1] != '/' {
r.Get(urlPath, http.RedirectHandler(urlPath+"/", 301).ServeHTTP)
urlPath += "/"
}
r.Get(urlPath+"*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
file := strings.Replace(r.RequestURI, urlPath, "/", 1)
if _, err := os.Stat(root + file); os.IsNotExist(err) {
http.ServeFile(w, r, path.Join(root, "index.html"))
return
}
fs.ServeHTTP(w, r)
}))
}