app/messenger/engine.go

48 lines
947 B
Go
Raw Normal View History

2021-12-17 03:46:04 +00:00
package messenger
import (
"bytes"
_ "embed"
"html/template"
"github.com/vanng822/go-premailer/premailer"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
)
//go:embed base.gohtml
var mailTmpl string
var engine *template.Template
var app App
func init() {
md := goldmark.New(
goldmark.WithExtensions(extension.GFM),
)
engine = template.Must(template.New("email").Funcs(template.FuncMap{
"ToHTML": func(mdtext string) (string, error) {
var buf bytes.Buffer
if err := md.Convert([]byte(mdtext), &buf); err != nil {
return "", err
}
return buf.String(), nil
},
}).Parse(mailTmpl))
}
func Parse(b *Base) (string, error) {
b.App = app
buf := &bytes.Buffer{}
err := engine.Execute(buf, b)
if err != nil {
return "", err
}
pre, err := premailer.NewPremailerFromString(buf.String(), premailer.NewOptions())
if err != nil {
return "", err
}
html, err := pre.Transform()
return html, err
}