package main import ( "encoding/json" "log" "os" "text/template" "github.com/gomarkdown/markdown" "github.com/gomarkdown/markdown/html" "github.com/gomarkdown/markdown/parser" "fmt" "net/http" ) type Config struct { Port uint } type Page struct { Title string MarkDown []byte HTML string Navigation string } 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.Println("Loading config.json") cfgfile, err := os.Open("config.json") if err != nil { log.Fatal("Error reading config.json!") return } defer cfgfile.Close() decoder := json.NewDecoder(cfgfile) Config := Config{} err = decoder.Decode(&Config) if err != nil { log.Fatal("Can't decode config.json!") return } fmt.Printf("Starting listener on :%v", Config.Port) http.Handle("/static/", http.FileServer(http.Dir("./"))) http.HandleFunc("/", httpRootHandler) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", Config.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 "Hoem" }