aboutsummaryrefslogtreecommitdiff
path: root/modules/services/nixos/jta/main.go
blob: 3e5fc1ffe1cf668389d0b04914480817c5022856 (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
package main

import (
	"bytes"
	_ "embed"
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/extension"
)

// Configure Goldmark with GitHub Flavored Markdown
var mdParser = goldmark.New(
	goldmark.WithExtensions(
		extension.GFM,
	),
)

//go:embed md_template.html
var mdTemplate string

//go:embed style.css
var styleCSS string

//go:embed index.html
var indexHTML string

var pageTmpl = template.Must(template.New("md_template.html").Parse(mdTemplate))

func serveMarkdown(w http.ResponseWriter, r *http.Request) {
	// Prevent path traversal
	clean := filepath.Clean(r.URL.Path)
	path := filepath.Join(rootDir, strings.TrimPrefix(clean, "/"))

	mdBytes, err := os.ReadFile(path)
	if err != nil {
		http.NotFound(w, r)
		return
	}

	var buf bytes.Buffer
	if err := mdParser.Convert(mdBytes, &buf); err != nil {
		http.Error(w, "failed to render markdown", 500)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	pageTmpl.Execute(w, map[string]template.HTML{
		"Content": template.HTML(buf.String()),
	})
}

var rootDir = "."

func main() {
	if envRootDir := os.Getenv("ROOT_DIR"); envRootDir != "" {
		rootDir = envRootDir
	}

	fs := http.FileServer(http.Dir(rootDir))
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" || r.URL.Path == "/index.html" {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.Write([]byte(indexHTML))
			return
		}

		if r.URL.Path == "/style.css" {
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
			w.Write([]byte(styleCSS))
			return
		}

		// Intercept markdown files
		if strings.HasSuffix(r.URL.Path, ".md") {
			serveMarkdown(w, r)
			return
		}

		// Otherwise serve normally
		fs.ServeHTTP(w, r)
	})

	http.ListenAndServe(":"+port, nil)
}