-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
74 lines (62 loc) · 1.61 KB
/
main.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
package main
import (
"fmt"
"gomodest-template/samples"
"log"
"net/http"
"os"
"path/filepath"
"strings"
rl "github.com/adnaan/renderlayout"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
_ "github.com/mattn/go-sqlite3"
)
func main() {
index, err := rl.New(
rl.Layout("index"),
rl.DisableCache(true),
rl.Debug(true),
rl.DefaultData(func(w http.ResponseWriter, r *http.Request) (rl.D, error) {
return rl.D{
"route": r.URL.Path,
"app_name": "gomodest-template",
}, nil
}))
if err != nil {
log.Fatal(err)
}
if err != nil {
log.Fatal(err)
}
r := chi.NewRouter()
r.Use(middleware.Compress(5))
r.Use(middleware.StripSlashes)
r.NotFound(index("404"))
r.Get("/", index("home", rl.StaticData(rl.D{"hello": "world"})))
r.Route("/samples", samples.Router(index))
workDir, _ := os.Getwd()
public := http.Dir(filepath.Join(workDir, "./", "public", "assets"))
staticHandler(r, "/static", public)
fmt.Println("listening on http://localhost:3000")
err = http.ListenAndServe(":3000", r)
if err != nil {
log.Fatal(err)
}
}
func staticHandler(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit any URL parameters.")
}
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
fs := http.StripPrefix(pathPrefix, http.FileServer(root))
fs.ServeHTTP(w, r)
})
}