package main import ( "os" "strings" ) type Post struct { Slug string Content string Title string Tags []string Created string Published bool } func loadPosts(directory string) map[string]*Post { entries, err := os.ReadDir(directory) if err != nil { panic(err) } posts := map[string]*Post{} for _, entry := range entries { fileName := entry.Name() if !strings.HasSuffix(fileName, ".md") { continue } baseName := strings.TrimSuffix(fileName, ".md") content := load("posts/" + fileName) post := &Post{ Slug: baseName, } if strings.HasPrefix(content, "---\n") { end := strings.Index(content[4:], "---\n") + 4 frontmatter := content[4:end] content = content[end+4:] parseFrontmatter(frontmatter, func(key, value string) { switch key { case "title": post.Title = value case "tags": post.Tags = strings.Split(value, " ") case "created": post.Created = value case "published": post.Published = value == "true" } }) } post.Content = content posts[baseName] = post } return posts } func parseFrontmatter(frontmatter string, assign func(key string, value string)) { lines := strings.Split(frontmatter, "\n") for _, line := range lines { colon := strings.Index(line, ":") if colon == -1 { continue } assign(line[:colon], strings.TrimSpace(line[colon+1:])) } }