85 lines
1.7 KiB
Go
85 lines
1.7 KiB
Go
|
package gomailer
|
||
|
|
||
|
import (
|
||
|
"log"
|
||
|
"os"
|
||
|
"path"
|
||
|
"strings"
|
||
|
"golang.org/x/net/html"
|
||
|
"github.com/vanng822/go-premailer/premailer"
|
||
|
)
|
||
|
|
||
|
func Inline(arg string) {
|
||
|
out := LoadTemplate(arg, true)
|
||
|
|
||
|
dir := path.Dir(arg)
|
||
|
ext := path.Ext(arg)
|
||
|
base := strings.ReplaceAll(path.Base(arg), ext, "")
|
||
|
output_file := path.Join(dir, base+"_inlined"+ext)
|
||
|
log.Printf("Template: %s -> %s", arg, output_file)
|
||
|
|
||
|
f, err := os.Create(output_file)
|
||
|
if err != nil {
|
||
|
log.Fatal("error inlining html: " + err.Error())
|
||
|
}
|
||
|
_, err = f.WriteString(out)
|
||
|
|
||
|
if err != nil {
|
||
|
log.Fatal("error inlining html: " + err.Error())
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func LoadTemplate(template string, inline bool) (string) {
|
||
|
rawhtml, err := os.ReadFile(template)
|
||
|
if err != nil {
|
||
|
log.Fatal("error loading template: " + err.Error())
|
||
|
}
|
||
|
|
||
|
if inline {
|
||
|
prem, err := premailer.NewPremailerFromBytes(rawhtml, premailer.NewOptions())
|
||
|
if err != nil {
|
||
|
log.Fatal("error inlining html: " + err.Error())
|
||
|
}
|
||
|
|
||
|
inlinehtml, err := prem.Transform()
|
||
|
if err != nil {
|
||
|
log.Fatal("error transforming html: " + err.Error())
|
||
|
}
|
||
|
return inlinehtml
|
||
|
}
|
||
|
|
||
|
return string(rawhtml)
|
||
|
}
|
||
|
|
||
|
func FindSrcInHtml(doc string) []string {
|
||
|
var results []string
|
||
|
reader := strings.NewReader(doc)
|
||
|
if document, err := html.Parse(reader); err == nil {
|
||
|
|
||
|
var parser func(*html.Node)
|
||
|
parser = func(n *html.Node) {
|
||
|
if n.Type == html.ElementNode && n.Data == "img" {
|
||
|
|
||
|
var imgSrcUrl string
|
||
|
|
||
|
for _, element := range n.Attr {
|
||
|
if element.Key == "src" {
|
||
|
imgSrcUrl = element.Val
|
||
|
log.Print("found image:" + imgSrcUrl)
|
||
|
results = append(results, imgSrcUrl)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||
|
parser(c)
|
||
|
}
|
||
|
|
||
|
}
|
||
|
parser(document)
|
||
|
} else {
|
||
|
log.Fatalln("Parse html error", err)
|
||
|
}
|
||
|
return results
|
||
|
}
|