-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
119 lines (97 loc) · 2.57 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"log"
"net/http"
"os"
"path"
"strings"
)
var ResourcesPath = "/" + RESOURCE_DIR + "/"
func check(funcName string, err error) {
if err != nil {
log.Fatal(funcName, " ", err)
}
}
// Handle the resources serving them statically
var HandlerResources = http.StripPrefix(ResourcesPath,
http.FileServer(http.Dir("."+ResourcesPath)),
)
// Handle the homepage ("", "index.html", "index", "home.html", "home")
func HandlerHome(w http.ResponseWriter, r *http.Request) {
var page = strings.ToUpper(strings.TrimSuffix(r.URL.Path[1:], ".html"))
switch page {
case "", "INDEX", "HOME", "BLOG":
err := Compose(w, "home.tmpl", Cache.GenSnippets())
check("HandlerHome", err)
default:
Handle404(w, r)
}
}
// Handle the 404 Error
func Handle404(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
err := Compose(w, "404.tmpl", nil)
check("Handle404", err)
}
// Handle the Blog (.../Blog or .../Blog/...)
func HandlerBlog(w http.ResponseWriter, r *http.Request) {
var (
content []byte
requested string
err error
)
// Get the unique identifier of the requested article
_, requested = path.Split(r.URL.Path)
if requested == "" {
HandlerHome(w, r)
return
}
requested = strings.TrimSuffix(requested, ".html")
// Check if it's on cache
if article := Cache.SelectArticle(requested); article != nil {
err = Compose(w, "article.tmpl", article)
if err == nil {
return
}
log.Println("HandlerBlog", "Cache.SelectArticle", err)
Cache.Remove(requested)
}
// Check inside the contents
log.Println(Cache.savedArticles, "["+requested+"]")
content, err = os.ReadFile(path.Join(BLOG_FOLDER, requested+".html"))
if err != nil {
if !os.IsNotExist(err) {
log.Println(err)
}
Handle404(w, r)
return
}
w.Write(content)
}
// Load template and create missing folders
func InitializeServer() {
// Loads all settings and paths
LoadSettings()
// Load all templates from folders
LoadTemplates(TEMPLATE_FOLDER)
// Recreate missing folders
check("HealDirectories", HealDirectories())
GenLastArticles()
}
func main() {
// Initialize server loading templates
InitializeServer()
// Manage changes in the articles (new / edited / deleted)
go Detect(ARTICLE_FOLDER, ManageContents)
// Manage changes in the templates
go Detect(TEMPLATE_FOLDER, UpdateTemplates)
// All the resources with static handles
http.Handle(ResourcesPath, HandlerResources)
// Homepage
http.HandleFunc("/", HandlerHome)
// Blog
http.HandleFunc("/blog/", HandlerBlog)
// Launch server
err := http.ListenAndServe(":8080", nil)
check("ListenAndServe", err)
}