Markdown Response
Learn how to serve Markdown content in Iris.
Basic Markdown Response
go
package main
import (
"github.com/kataras/iris/v12"
"github.com/russross/blackfriday/v2"
)
func main() {
app := iris.New()
app.Get("/markdown", func(ctx iris.Context) {
markdown := []byte(`
# Hello World
This is a markdown document:
* Item 1
* Item 2
* Item 3
`)
html := blackfriday.Run(markdown)
ctx.HTML(string(html))
})
app.Listen(":8080")
}
Markdown File Serving
go
app.Get("/doc/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
content, err := os.ReadFile("./docs/" + name + ".md")
if err != nil {
ctx.StopWithError(iris.StatusNotFound, err)
return
}
html := blackfriday.Run(content)
ctx.HTML(string(html))
})
Custom Rendering
go
func renderMarkdown(content []byte) []byte {
extensions := blackfriday.WithExtensions(
blackfriday.CommonExtensions |
blackfriday.AutoHeadingIDs |
blackfriday.NoEmptyLineBeforeBlock,
)
return blackfriday.Run(content, extensions)
}
app.Get("/custom", func(ctx iris.Context) {
content := []byte("# Custom Markdown")
html := renderMarkdown(content)
ctx.HTML(string(html))
})
Best Practices
Security:
- Sanitize input
- Validate content
- Set security headers
- Handle file access
- Monitor usage
Performance:
- Cache rendered content
- Enable compression
- Optimize rendering
- Monitor response times
- Handle timeouts
Content:
- Validate markdown
- Handle edge cases
- Support extensions
- Document syntax
- Regular updates
Maintenance:
- Monitor errors
- Update dependencies
- Clean content
- Document changes
- Review security