-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
64 lines (51 loc) · 1.41 KB
/
router.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
package router
import (
"fmt"
"html/template"
"io/fs"
"net/http"
"time"
"github.com/a10adotapp/blog.a10a.app/2023/1025/router/helper"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/chi/v5"
)
func NewRouter(fsys fs.FS) *chi.Mux {
tmpl, err := template.ParseFS(fsys, []string{
"static/index.html",
}...)
if err != nil {
panic(err)
}
router := chi.NewRouter()
router.Use(middleware.Timeout(10 * time.Second))
router.Use(middleware.Logger)
router.Route("/api", func(r chi.Router) {
r.Get("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, "{\"message\":\"hello from api\"}")
}))
})
router.Route("/", func(r chi.Router) {
r.Get("/scripts/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
subFsys, err := fs.Sub(fsys, "static")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
http.FileServer(http.FS(subFsys)).ServeHTTP(w, r)
}))
r.Get("/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pageData := &struct {
Message string
}{
Message: "hello from server",
}
if err := tmpl.ExecuteTemplate(w, helper.ParseTemplateFilename(r.URL.Path), pageData); err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
}
}))
})
return router
}