summaryrefslogtreecommitdiff
path: root/main.go
blob: b0c07871f29f01a32016c8d3c998f6c4b7cba6c2 (plain)
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
package main

import (
	"embed"
	"encoding/base64"
	"flag"
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/gomarkdown/markdown"
	"github.com/gomarkdown/markdown/parser"
)

//go:embed templates/* assets/*
var content embed.FS

type Page struct {
	Title   string
	Body    template.HTML
	CSS     template.CSS
	Favicon template.URL
}

func main() {
	port := flag.Int("port", 8080, "Port to run the server on")
	flag.Parse()
	addr := fmt.Sprintf(":%d", *port)

	http.HandleFunc("/", handler)
	log.Printf("Server is running on http://localhost%s\n", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	if path == "/" {
		path = "/home"
	}

	filePath := fmt.Sprintf("assets/md%s.md", path)
	mdContent, err := content.ReadFile(filePath)
	if err != nil {
		http.Error(w, "Page not found", http.StatusNotFound)
		return
	}

	cssContent, err := content.ReadFile("templates/styles.css")
	if err != nil {
		http.Error(w, "Stylesheet not found", http.StatusInternalServerError)
		return
	}

	htmlContent := convertMarkdownToHTML(mdContent)

	faviconBytes, err := content.ReadFile("assets/favicon.png")
	if err != nil {
		http.Error(w, "Favicon not found", http.StatusInternalServerError)
		return
	}
	faviconBase64 := fmt.Sprintf("data:image/png;base64,%s", base64.StdEncoding.EncodeToString(faviconBytes))

	page := Page{
		Title:   "Blaster4385",
		Body:    template.HTML(htmlContent),
		CSS:     template.CSS(string(cssContent)),
		Favicon: template.URL(faviconBase64),
	}

	w.Header().Set("Content-Type", "text/html")
	renderTemplate(w, "index.html", page)
}

func convertMarkdownToHTML(markdownContent []byte) string {
	mdParser := parser.New()

	html := markdown.ToHTML(markdownContent, mdParser, nil)
	return string(html)
}

func renderTemplate(w http.ResponseWriter, tmpl string, p Page) {
	tmplContent, err := content.ReadFile("templates/" + tmpl)
	if err != nil {
		http.Error(w, "Template not found", http.StatusInternalServerError)
		return
	}

	t, err := template.New(tmpl).Parse(string(tmplContent))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = t.Execute(w, p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}