Golang にて markdown 表記ができる blackfriday を使う

使ったモジュール

サンプルコード

  • blackfriday.HardLineBreak - 改行を<br>に変換する
  • blackfriday.Autolink - http:// 〜 から始めるテキストにリンクをつける
  • blackfriday.HrefTargetBlank - ???

markdown.go

package main

import (
	"fmt"
	"html/template"

	"github.com/microcosm-cc/bluemonday"
	"gopkg.in/russross/blackfriday.v2"
)

func main() {

	s := `
# title

* list1
* list2


## title2

this is markdown.
hello, world.

https://github.com/psychedelicnekopunch/go-sample

[go-sample](https://github.com/psychedelicnekopunch/go-sample)
`

	renderer := blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{
		Flags: blackfriday.HrefTargetBlank,
	})
	output := blackfriday.Run([]byte(s), blackfriday.WithExtensions(blackfriday.HardLineBreak + blackfriday.Autolink), blackfriday.WithRenderer(renderer))
	html := bluemonday.UGCPolicy().SanitizeBytes(output)

	fmt.Print(template.HTML(string(html)))
}

go.mod

module github.com/psychedelicnekopunch/go-sample

go 1.14

require (
	github.com/microcosm-cc/bluemonday v1.0.2
	gopkg.in/russross/blackfriday.v2 v2.0.1
)

replace gopkg.in/russross/blackfriday.v2 => github.com/russross/blackfriday/v2 v2.0.1

確認

$ go run markdown.go

<h1>title</h1>

<ul>
<li>list1<br>
</li>
<li>list2<br>
</li>
</ul>

<h2>title2</h2>

<p>this is markdown.<br>
hello, world.</p>

<p><a href="https://github.com/psychedelicnekopunch/go-sample" rel="nofollow">https://github.com/psychedelicnekopunch/go-sample</a></p>

<p><a href="https://github.com/psychedelicnekopunch/go-sample" rel="nofollow">go-sample</a></p>