1

I'm writing a webhook in Go that sends me an email with the diff for every commit to certain repository. Right now I am sending the diff as raw text like this:

https://github.com/ee92/go-lambda/commit/ac56fc2cfe86c50e9d73ecb0f8db74c672e205cd.diff

I wish to send it as pretty formatted HTML with color like you see on github or bitbucket so it will be easier to read what changed. Really stumped on how to go about this. Appreciate any advice. Thanks.

Egor Egorov
  • 705
  • 3
  • 10
  • 22
  • 2
    Maybe use something like [go-diff](https://github.com/sourcegraph/go-diff) and then pass it to some html template? – yname Apr 15 '18 at 05:37
  • You could also keep the diff as-is and handle the colouring client-side (via a plugin or similar to your e-mail reader); that way you would also get syntax colouring for diffs sent by others. – jsageryd Apr 15 '18 at 06:56

1 Answers1

1

You could use the stdlib html/template library to make a pretty HTML template and pass your raw string as a param:

https://golang.org/pkg/html/template/

import "text/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")

will produce this:

Hello, <script>alert('you have been pwned')</script>!

So in your case, define a template in a separate file, read it in, and then call

t, err := template.ParseFiles("./path/to/template.html")
if err != nil {
    log.Fatal(err)
}

err = t.ExecuteTemplate(out, "T", rawDiffString)
if err != nil {
    log.Fatal(err)
}

which will take your diff string and stick it into the template wherever you defined the template variable.

You'll have to read the spec for how Go parses through the HTML template to properly format your HTML file.