4
0

template.go 1.1 KB

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