This repository has been archived on 2025-09-28. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
plaintext-encyclopedia/main.go

88 lines
2 KiB
Go
Raw Normal View History

2024-08-27 11:55:01 +02:00
package main
2024-08-28 20:29:34 +02:00
// Copyright (c) 2024 Julian Müller (ChaoticByte)
2024-08-27 11:55:01 +02:00
import (
"html/template"
"log"
"net/http"
"os"
2024-08-28 19:49:23 +02:00
"path"
2024-08-27 11:55:01 +02:00
"strings"
)
var logger *log.Logger
var appTemplate *template.Template = template.New("app")
var db Database
2024-08-27 11:55:01 +02:00
type TemplateData struct {
Title string
2024-08-29 13:29:39 +02:00
SiteDescription string
TOC map[string]string
2024-08-27 11:55:01 +02:00
EntryTitle string
2024-08-29 13:29:39 +02:00
Entry string
Footer []template.HTML
2024-08-27 11:55:01 +02:00
}
func loadTemplate() {
data, err := os.ReadFile(TemplateFile)
if err != nil { logger.Panicln(err) }
2024-08-27 11:55:01 +02:00
appTemplate.Parse(string(data))
}
func handleApplication(w http.ResponseWriter, req *http.Request) {
var entry string
var err error
entryId := path.Base(req.URL.Path)
if entryId != "/" {
2024-08-27 11:55:01 +02:00
// load entry
entry = db.Entries[entryId]
2024-08-28 19:49:23 +02:00
if entry == "" { // redirect if entry doesn't exist (or is empty)
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
}
2024-08-27 11:55:01 +02:00
}
err = appTemplate.ExecuteTemplate(
w, "app",
2024-08-29 13:29:39 +02:00
TemplateData{
TOC: db.Titles,
2024-08-29 13:29:39 +02:00
Entry: entry,
Title: MainTitle,
EntryTitle: db.Titles[entryId],
2024-08-29 13:29:39 +02:00
Footer: FooterContent,
SiteDescription: SiteDescription,
})
2024-08-27 11:55:01 +02:00
if err != nil { logger.Println(err) }
}
2024-08-28 19:49:23 +02:00
func handleSearchAPI(w http.ResponseWriter, req *http.Request) {
searchQuery := path.Base(req.URL.Path)
if searchQuery == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
results := db.searchForIds(searchQuery)
for i, r := range results {
results[i] = r + "|" + db.Titles[r]
}
2024-08-28 19:49:23 +02:00
w.Write([]byte(strings.Join(results, "\n")))
}
2024-08-27 11:55:01 +02:00
func main() {
// get logger
logger = log.Default()
// load template
loadTemplate()
// build db
db = BuildDB(EntriesDirectory)
2024-08-27 11:55:01 +02:00
// handle static files
staticHandler := http.StripPrefix("/static/", http.FileServer(http.Dir(StaticDirectory)))
http.Handle("/static/", staticHandler)
// handle application
http.HandleFunc("/", handleApplication)
2024-08-28 19:49:23 +02:00
http.HandleFunc("/search/", handleSearchAPI)
2024-08-27 11:55:01 +02:00
// start server
logger.Println("Starting server on", ServerListen)
err := http.ListenAndServe(ServerListen, nil)
if err != nil { logger.Panicln(err) }
2024-08-27 11:55:01 +02:00
}