template.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. funcMap := sprig.TxtFuncMap()
  26. delete(funcMap, "env")
  27. delete(funcMap, "expandenv")
  28. delete(funcMap, "getHostByName")
  29. t = t.Funcs(funcMap)
  30. t, err = t.Parse(templateText)
  31. if err != nil {
  32. return nil, fmt.Errorf("error parsing file: %w", err)
  33. }
  34. return &TemplateReporter{template: t}, nil
  35. }
  36. // writeTemplate renders the findings using the user-provided template.
  37. // https://www.digitalocean.com/community/tutorials/how-to-use-templates-in-go
  38. func (t *TemplateReporter) Write(w io.WriteCloser, findings []Finding) error {
  39. if err := t.template.Execute(w, findings); err != nil {
  40. return err
  41. }
  42. return nil
  43. }