MdGo

Manipulate Markdown files by extracting fenced code blocks and writing them to output files.
Usage (Go examples)
Note: mdgo delegates file writing to the writerFile function you pass to New(...).
That function is responsible for creating directories if needed. This makes mdgo
flexible (it can write to disk, to an in-memory filesystem, or to custom sinks).
- Basic example with a writer that ensures directories exist:
package main
import (
"os"
"path/filepath"
"fmt"
"github.com/cdvelop/mdgo"
)
func main() {
root := "/project/root"
dest := "deploy"
// writer that creates directories before writing
writer := func(name string, data []byte) error {
if err := os.MkdirAll(filepath.Dir(name), 0o755); err != nil {
return err
}
return os.WriteFile(name, data, 0o644)
}
// Create mdgo instance
m := mdgo.New(root, dest, writer)
// Provide input from a file path relative to root. You must also pass a reader
// function that knows how to read from that path (e.g. using os.ReadFile).
m.InputPath("templates/server.md", func(name string) ([]byte, error) {
return os.ReadFile(filepath.Join(root, name))
})
// Extract code to an output file. The output extension decides which fenced
// code blocks are picked (.go -> ```go, .js -> ```javascript, .css -> ```css).
if err := m.Extract("main.go"); err != nil {
fmt.Println("extract error:", err)
}
}
- Provide input directly from memory (handy for tests):
m := mdgo.New("/project/root", "deploy", writer)
m.InputByte([]byte("# Example\n```go\npackage main\n```"))
_ = m.Extract("inmem.go")
- Use an embed.FS or any custom reader with
InputEmbed:
// reader: func(name string)([]byte, error) - can read from embed.FS or other sources
m := mdgo.New("/project/root", "deploy", writer)
m.InputEmbed("templates/server.md", func(name string) ([]byte, error) {
// e.g. return embeddedFS.ReadFile(name)
return nil, nil
})
_ = m.Extract("main.go")
- Optional logger
// Print internal actions
m.SetLogger(func(v ...any) { fmt.Println(v...) })
Supported output extensions (determine which fenced blocks are extracted):
.go -> ```go
.js -> ```javascript
.css -> ```css
If you want mdgo to write files on disk, pass a writerFile that creates
necessary directories (as shown above). If you use a custom writer (for example
to capture output in memory or to write into an embed FS), mdgo will call the
writer exactly with the destination path and file content.