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
|
package render
import (
"fmt"
"log/slog"
"net/http"
"strings"
index "physick.ru/Index"
settings "physick.ru/Settings"
)
type IndexTemplateContents struct {
LastArticles []index.Article
Content string
Tags []index.Tag
}
func RegisterEndpoints() {
// http.Handle("static/", http.FileServer(http.FS(os.DirFS(settings.Current.StaticLocation))))
http.HandleFunc("/articles/{name}", test)
http.HandleFunc("/.well-known/discord", discord_verification)
http.HandleFunc("/", mux)
}
func discord_verification(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, fmt.Sprintf("%s/discord.txt", settings.Current.StaticLocation))
}
func mux(w http.ResponseWriter, r *http.Request) {
// slog.Info("Request", slog.String("URL", r.URL.String()))
if r.URL.String() == "/favicon.ico" {
http.ServeFile(w, r, fmt.Sprintf("%s/favicon.ico", settings.Current.StaticLocation))
}
if strings.HasPrefix(r.URL.String(), "/static") {
var filePath = strings.Replace(r.URL.String(), "/static", settings.Current.StaticLocation, 1)
http.ServeFile(w, r, filePath)
return
}
common(w, r)
}
func common(w http.ResponseWriter, r *http.Request) {
var indexArticle, indexErr = getTemplate("index.html")
if indexErr != nil {
slog.Error("Failed to parse the template", slog.Any("Error", indexErr))
w.WriteHeader(http.StatusInternalServerError)
return
}
var recentArticles, dbErr = index.GetAllArticles()
if dbErr != nil {
slog.Error("Failed to get recent articles from database", slog.Any("Error", dbErr))
w.WriteHeader(http.StatusInternalServerError)
return
}
executeIndexTemplate(IndexTemplateContents{
LastArticles: recentArticles,
Content: indexArticle,
}, w)
}
func test(w http.ResponseWriter, r *http.Request) {
var requestedName = r.PathValue("name")
if len(requestedName) < 1 {
w.WriteHeader(http.StatusNotFound)
return
}
var article, dbErr = index.GetArticleByName(requestedName)
if dbErr != nil {
slog.Error("Failed to get an article from db", slog.Any("Error", dbErr))
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(article.DisplayName) < 1 {
w.WriteHeader(http.StatusNotFound)
return
}
var contents, fileErr = getTemplate(article.FileName)
if fileErr != nil {
w.WriteHeader(http.StatusNotFound)
return
}
var recentArticles, err = index.GetAllArticles()
if err != nil {
slog.Error("Failed to get recent articles from database", slog.Any("Error", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
executeIndexTemplate(IndexTemplateContents{
LastArticles: recentArticles,
Content: contents,
Tags: article.Tags,
}, w)
}
|