-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.go
61 lines (47 loc) · 1.19 KB
/
app.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
package web
import (
"embed"
"io/fs"
"log"
"net/http"
"os"
"github.com/alexedwards/flow"
"github.com/theandrew168/bloggulus/internal/middleware"
"github.com/theandrew168/bloggulus/internal/storage"
)
var (
pageSize = 15
)
//go:embed template
var templateFS embed.FS
type Application struct {
templates fs.FS
logger *log.Logger
storage *storage.Storage
}
func NewApplication(logger *log.Logger, storage *storage.Storage) *Application {
var templates fs.FS
if os.Getenv("DEBUG") != "" {
// reload templates from filesystem if var DEBUG is set
// NOTE: os.DirFS is rooted from where the app is ran, not this file
templates = os.DirFS("./internal/web/template/")
} else {
// else use the embedded template dir
templates, _ = fs.Sub(templateFS, "template")
}
app := Application{
templates: templates,
logger: logger,
storage: storage,
}
return &app
}
func (app *Application) Router() http.Handler {
mux := flow.New()
mux.NotFound = http.HandlerFunc(app.notFoundResponse)
mux.MethodNotAllowed = http.HandlerFunc(app.methodNotAllowedResponse)
mux.Use(middleware.RecoverPanic)
mux.Use(middleware.SecureHeaders)
mux.HandleFunc("/", app.HandleIndex, "GET")
return mux
}