Last active
September 24, 2024 21:14
-
-
Save huanlin/10b45188f1818ae67acc03d797be6046 to your computer and use it in GitHub Desktop.
Parsing a Hugo markdown file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"regexp" | |
"gopkg.in/yaml.v2" | |
) | |
// FrontMatter struct to hold parsed front matter | |
type FrontMatter struct { | |
Title string `yaml:"title"` | |
Description string `yaml:"description"` | |
Date string `yaml:"date"` | |
} | |
// MarkdownFile struct to hold front matter and body content | |
type MarkdownFile struct { | |
FrontMatter FrontMatter | |
Body []byte | |
} | |
// Function to parse the markdown file | |
func parseMarkdownFile(filename string) (*MarkdownFile, error) { | |
// Read the entire markdown file | |
content, err := ioutil.ReadFile(filename) | |
if err != nil { | |
return nil, err | |
} | |
// Regular expression to find the front matter | |
re := regexp.MustCompile(`(?s)^---\n(.*?)\n---\n(.*)$`) | |
matches := re.FindStringSubmatch(string(content)) | |
if len(matches) != 3 { | |
return nil, fmt.Errorf("front matter not found") | |
} | |
// Parse front matter | |
var frontMatter FrontMatter | |
err = yaml.Unmarshal([]byte(matches[1]), &frontMatter) | |
if err != nil { | |
return nil, err | |
} | |
// Body content as a byte array | |
body := []byte(matches[2]) | |
return &MarkdownFile{ | |
FrontMatter: frontMatter, | |
Body: body, | |
}, nil | |
} | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("Usage: go run main.go <markdown-file>") | |
return | |
} | |
filename := os.Args[1] | |
mdFile, err := parseMarkdownFile(filename) | |
if err != nil { | |
fmt.Printf("Error parsing markdown file: %v\n", err) | |
return | |
} | |
// Output the parsed front matter and body | |
fmt.Printf("Title: %s\n", mdFile.FrontMatter.Title) | |
fmt.Printf("Description: %s\n", mdFile.FrontMatter.Description) | |
fmt.Printf("Date: %s\n", mdFile.FrontMatter.Date) | |
fmt.Printf("Body:\n%s\n", string(mdFile.Body)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment