File: validate.go

package info (click to toggle)
golang-github-smallstep-crypto 0.63.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 3,800 kB
  • sloc: sh: 66; makefile: 50
file content (41 lines) | stat: -rw-r--r-- 1,011 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package templates

import (
	"encoding/json"
	"errors"
	"fmt"
	"text/template"
)

// ValidateTemplate validates a text template results in valid JSON
// when it's executed with empty template data. If template execution
// results in invalid JSON, the template is invalid. When the template
// is valid, it can be used safely. A valid template can still result
// in invalid JSON when non-empty template data is provided.
func ValidateTemplate(data []byte, funcMap template.FuncMap) error {
	if len(data) == 0 {
		return nil
	}

	// prepare the template with our template functions
	_, err := template.New("template").Funcs(funcMap).Parse(string(data))
	if err != nil {
		return fmt.Errorf("error parsing template: %w", err)
	}

	return nil
}

// ValidateTemplateData validates that template data is
// valid JSON.
func ValidateTemplateData(data []byte) error {
	if len(data) == 0 {
		return nil
	}

	if ok := json.Valid(data); !ok {
		return errors.New("error validating json template data")
	}

	return nil
}