/
goingup.go
75 lines (61 loc) · 1.8 KB
/
goingup.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
package goingup
import (
"fmt"
"html/template"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
// App represents the whole goingup application
type App struct {
Options *Config
Pages []*Page
Menus map[string]*Menu
Templates *template.Template
Content map[string]string
}
// NewApp creates a new App instance
func NewApp() *App {
return &App{
Options: NewConfig(),
Pages: make([]*Page, 0),
Menus: make(map[string]*Menu, 0),
}
}
func (a *App) AddPage(page *Page) {
a.Pages = append(a.Pages, page)
}
func (a *App) AddMenu(name string, menu *Menu) {
a.Menus[name] = menu
}
// Run finalizes all options and calls the ListenAndServe function to serve
// requests
func (a *App) Run() {
fmt.Println("GoingUp App Starting")
r := mux.NewRouter()
fs := http.FileServer(http.Dir(a.Options.StaticAssetsDir))
r.PathPrefix(a.Options.StaticAssetsURL).Handler(http.StripPrefix(a.Options.StaticAssetsURL, fs))
fmt.Println("Parsing Templates")
a.Templates = template.Must(template.ParseGlob(a.Options.TemplateDir + "/*"))
fmt.Println("Parsing Content")
a.Content = parseContentGlob(a.Options.ContentDir + "/*.md")
for _, page := range a.Pages {
content := ""
if page.ContentName != "" {
if val, exists := a.Content[page.ContentName]; exists {
content = val
}
}
page.Content = template.HTML(content)
r.HandleFunc(page.URL, makePageHandler(a, page))
}
strPort := strconv.Itoa(a.Options.Port)
fmt.Printf("Listening on %s\n", strPort)
http.ListenAndServe(":"+strPort, newLogHandler(r))
}
func newLogHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}