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

76 lines
1.8 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 {
TOC []string
Entry string
Title string
EntryTitle string
}
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
2024-08-28 19:49:23 +02:00
entryName := path.Base(req.URL.Path)
if entryName != "/" {
2024-08-27 11:55:01 +02:00
// load entry
entry = db.Entries[entryName]
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",
TemplateData{TOC: db.Keys, Entry: entry, Title: MainTitle, EntryTitle: entryName})
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.search(searchQuery)
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
}