template.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package report
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "text/template"
  7. "github.com/Masterminds/sprig"
  8. )
  9. type TemplateReporter struct {
  10. template *template.Template
  11. }
  12. var _ Reporter = (*TemplateReporter)(nil)
  13. func NewTemplateReporter(templatePath string) (*TemplateReporter, error) {
  14. if templatePath == "" {
  15. return nil, fmt.Errorf("template path cannot be empty")
  16. }
  17. file, err := os.ReadFile(templatePath)
  18. if err != nil {
  19. return nil, fmt.Errorf("error reading file: %w", err)
  20. }
  21. templateText := string(file)
  22. // TODO: Add helper functions like escaping for JSON, XML, etc.
  23. t := template.New("custom")
  24. t = t.Funcs(sprig.TxtFuncMap())
  25. t, err = t.Parse(templateText)
  26. if err != nil {
  27. return nil, fmt.Errorf("error parsing file: %w", err)
  28. }
  29. return &TemplateReporter{template: t}, nil
  30. }
  31. // writeTemplate renders the findings using the user-provided template.
  32. // https://www.digitalocean.com/community/tutorials/how-to-use-templates-in-go
  33. func (t *TemplateReporter) Write(w io.WriteCloser, findings []Finding) error {
  34. if err := t.template.Execute(w, findings); err != nil {
  35. return err
  36. }
  37. return nil
  38. }