/** * microblog in go * * get goldmark md parser * go get github.com/yuin/goldmark **/ package main import ( "html/template" "io/ioutil" "net/http" "os" "path/filepath" "strings" "github.com/yuin/goldmark" ) const articlesDir = "data/articles" func main() { //http.HandleFunc("/", handlePage) println("Server startet http://localhost:8085") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { println("start HandleFunc") path := r.URL.Path ext := filepath.Ext(path) switch ext { case ".css": println("css gefunden. path: " + path) w.Header().Set("Content-Type", "text/css") case ".jpg", ".jpeg": w.Header().Set("Content-Type", "image/jpeg") case ".png": w.Header().Set("Content-Type", "image/png") case ".gif": w.Header().Set("Content-Type", "image/gif") default: println("rufe handlePage") handlePage(w,r) return } http.ServeFile(w, r, "."+path) return }) http.ListenAndServe(":8085", nil) } func handlePage(w http.ResponseWriter, r *http.Request) { path := r.URL.Path if path == "/" { path = "/index" } // Entferne führenden Slash pagePath := strings.TrimPrefix(path, "/") // Baue den Pfad zur Markdown-Datei mdPath := filepath.Join(articlesDir, filepath.FromSlash(pagePath)+".md") // Überprüfe, ob die Datei existiert if _, err := os.Stat(mdPath); os.IsNotExist(err) { http.NotFound(w, r) return } // Datei lesen data, err := ioutil.ReadFile(mdPath) if err != nil { http.Error(w, "Fehler beim Lesen der Seite", 500) return } // Markdown in HTML umwandeln mit Goldmark htmlContent, err := markdownToHTML(data) if err != nil { http.Error(w, "Fehler bei der Konvertierung", 500) return } // Seiten-Titel aus Dateiname oder erster Überschrift (optional) title := filepath.Base(pagePath) title = strings.ReplaceAll(title, "_", " ") title = strings.Title(title) // HTML-Template tmpl := ` {{.Title}}

{{.Title}}

{{.Content}}

Startseite

` t, err := template.New("page").Parse(tmpl) if err != nil { http.Error(w, "Template Fehler", 500) return } t.Execute(w, map[string]interface{}{ "Title": title, "Content": template.HTML(htmlContent), }) } // Funktion, um Markdown mit Goldmark in HTML umzuwandeln func markdownToHTML(md []byte) ([]byte, error) { var buf strings.Builder mdParser := goldmark.New() if err := mdParser.Convert(md, &buf); err != nil { return nil, err } return []byte(buf.String()), nil }