Use markdown as config
By Jonas Plum on
Most of the time we use json or yaml files for configuration. But these lack the ability to display styled text or syntax-highlighted code samples. Markdown has these capabilities, but cannot be easily parsed to be used as a configuration file.
I created https://github.com/cugu/md to parse markdown into Go structs, similar to how encoding/json.Unmarshal works for json files.
The following example shows how to use the package.
1package main
2
3import (
4 "fmt"
5
6 "github.com/cugu/md"
7)
8
9type Text struct {
10 Title string `md:"heading"`
11 Description string `md:"paragraph"`
12}
13
14const example = `
15# Title
16A short description.
17`
18
19func main() {
20 var text Text
21 if err := md.Unmarshal([]byte(example), &text); err != nil {
22 fmt.Println(err)
23 return
24 }
25
26 fmt.Println(text.Title)
27 fmt.Println(text.Description)
28 // Output:
29 // Title
30 // A short description.
31}
Use case 1: Package definitions #
I started to create a simple package manager which uses markdown files for package definitions. Sections are used for the install and uninstall commands. GitHub renders these files as markdown, so headings and description paragraphs render nicely for humans, and the embedded code is syntax-highlighted as well.
1# Starship prompt
2
3Starship is a minimal, blazing-fast, and infinitely customizable prompt for any shell!
4
5## Install
6
7```bash
8#!/bin/bash
9
10# download starship and install it
11curl -fsSL https://starship.rs/install.sh -o install-starship.sh
12chmod +x install-starship.sh
13./install-starship.sh --bin-dir ~/bin --yes
14
15# more steps...
16```
17
18## Uninstall
19
20```bash
21...
Use case 2: End-to-end tests #
Another project I am working on processes received json events. This project uses markdown files for end-to-end testing. The input json and the expected output logs are defined in different markdown sections. Titles and paragraphs are used for description.
1# Test 1: Reply to Slack message
2
3Reply to a received Slack [message event](https://api.slack.com/events/message).
4
5## Event
6
7```json
8{
9 "type": "message",
10 "channel": "C123ABC456",
11 "user": "U123ABC456",
12 "text": "Hello Bob",
13 "ts": "1355517523.000005"
14}
15```
16
17## Output
18
19```log
20INFO "received message" type="message" text="Hello Bob"
21INFO "reply sent" msg="Hello Alice"
22```
Conclusion #
I'm happy if https://github.com/cugu/md is useful for your projects and for your feedback. I also consider adding features, e.g. marshalling if needed, but want to keep the package as simple as possible.