website/main.go

71 lines
1.5 KiB
Go
Raw Normal View History

2024-07-06 09:04:33 +00:00
package main
import (
"net/http"
"os"
"log"
"html/template"
)
type Index struct {
Title string
}
var data = &Index {
2024-07-07 14:08:10 +00:00
Title: "MBot",
2024-07-06 09:04:33 +00:00
}
2024-07-10 08:24:22 +00:00
func fileHandler(file string, path string) {
fs := http.FileServer(http.Dir("./" + file))
http.Handle("/" + path + "/", http.StripPrefix("/" + path + "/", fs))
}
2024-07-06 09:04:33 +00:00
func aboutHandler(w http.ResponseWriter, req *http.Request) {
templates := template.Must(template.ParseFiles(
"src/index.tmpl",
"src/pages/about.tmpl",
"src/components/navbar.tmpl",
"src/components/footer.tmpl",
))
err := templates.ExecuteTemplate(w, "base", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func indexHandler(w http.ResponseWriter, req *http.Request) {
templates := template.Must(template.ParseFiles(
"src/index.tmpl",
"src/pages/home.tmpl",
"src/components/navbar.tmpl",
"src/components/footer.tmpl",
))
err := templates.ExecuteTemplate(w, "base", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
if _, err := os.Stat("src/index.tmpl"); os.IsNotExist(err) {
log.Fatal("Template file does not exist:\n", err)
}
2024-07-10 08:24:22 +00:00
fileHandler("src/assets", "assets");
fileHandler("src/styles", "styles");
fileHandler("src/scripts", "scripts");
fileHandler("src/fonts", "fonts");
2024-07-06 09:04:33 +00:00
port := ":3939"
http.HandleFunc("/", indexHandler)
http.HandleFunc("/about", aboutHandler)
log.Println("Server running at http://localhost" + port)
http.ListenAndServe(port, nil)
}