Documentation ¶
Overview ¶
Package md implements functions to parse markdown into Go structs, similar to how JSON is parsed into Go structs.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Unmarshal ¶
Unmarshal takes a byte slice of markdown (md) and a non-nil pointer (v) as arguments. It parses the markdown into blocks and assigns the content of each block to the corresponding field in v. The function uses struct tags to map markdown block to fields in v. If a required block (one without the 'omitempty' option in its tag) is missing from the markdown, the function returns an error. If an unexpected block element is encountered, the function also returns an error.
Example ¶
package main import ( "fmt" "github.com/cugu/md" ) type Text struct { Title string `md:"heading"` Description string `md:"paragraph"` } const example = ` # Title A short description. ` func main() { var text Text if err := md.Unmarshal([]byte(example), &text); err != nil { fmt.Println(err) return } fmt.Println(text.Title) fmt.Println(text.Description) }
Output: Title A short description.
Example (Extended) ¶
package main import ( "fmt" "github.com/cugu/md" ) type ExtendedText struct { Title string `md:"heading"` Quote string `md:"blockquote"` Description string `md:"paragraph"` Break string `md:"thematic_break"` CodeBlock string `md:"code_block"` } const exampleExtended = "\n# Title\n\n> A quote.\n\nA short description.\n\n---\n\n```\ncode block\n```\n" func main() { var text ExtendedText if err := md.Unmarshal([]byte(exampleExtended), &text); err != nil { fmt.Println(err) return } fmt.Println(text.Title) fmt.Println(text.Quote) fmt.Println(text.Description) fmt.Println(text.Break) fmt.Println(text.CodeBlock) }
Output: Title A quote. A short description. code block
Example (Omitempty) ¶
package main import ( "fmt" "github.com/cugu/md" ) type OmitemptyText struct { Title string `md:"heading"` Quote string `md:"blockquote,omitempty"` Description string `md:"paragraph"` } const exampleOmitempty = ` # Title A short description. ` func main() { var text OmitemptyText if err := md.Unmarshal([]byte(exampleOmitempty), &text); err != nil { fmt.Println(err) return } fmt.Println(text.Title) fmt.Println(text.Quote) fmt.Println(text.Description) }
Output: Title A short description.
Types ¶
type Option ¶
type Option func(*config)
Option is a functional option type for the Unmarshal function.
func WithDisallowUnknownFields ¶
func WithDisallowUnknownFields() Option
WithDisallowUnknownFields is a functional option that allows you to disallow unknown fields in the markdown.
func WithParser ¶
WithParser is a functional option that allows you to set the parser to be used by Unmarshal.