doksie/main.go
2024-12-27 20:20:01 +02:00

69 lines
1.5 KiB
Go

package main
import (
"log"
"os"
"text/template"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
"fmt"
"net/http"
)
type Page struct {
Title string
MarkDown []byte
HTML string
Navigation string
}
const port = 6900
func mdToHTML(md []byte) []byte {
// create markdown parser with extensions
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
p := parser.NewWithExtensions(extensions)
doc := p.Parse(md)
// create HTML renderer with extensions
htmlFlags := html.CommonFlags | html.HrefTargetBlank
opts := html.RendererOptions{Flags: htmlFlags}
renderer := html.NewRenderer(opts)
return markdown.Render(doc, renderer)
}
func main() {
fmt.Printf("Starting listener on :%v", port)
http.Handle("/static/", http.FileServer(http.Dir("./")))
http.HandleFunc("/", httpRootHandler)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
func loadPage(fileUrl string) ([]byte, error) {
var fileContents, err = os.ReadFile(fileUrl)
if err != nil {
return nil, err
}
return fileContents, nil
}
func httpRootHandler(w http.ResponseWriter, r *http.Request) {
var p Page
t, _ := template.ParseFiles("page.html")
markdown, err := loadPage("content/index.md")
p.MarkDown = markdown
if err != nil {
log.Fatal("Can't open file")
}
p.HTML = string(mdToHTML(p.MarkDown))
p.Navigation = buildNav()
t.Execute(w, p)
}
func buildNav() string {
return "<a href=\"http://google.com\">Google.com</a>"
}