forked from adobe/rules_gitops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
81 lines (67 loc) · 2.06 KB
/
example_test.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package fasttemplate
import (
"fmt"
"io"
"net/url"
)
func ExampleTemplate() {
template := "http://{{host}}/?foo={{bar}}{{bar}}&q={{query}}&baz={{baz}}"
// Substitution map.
// Since "baz" tag is missing in the map, it will be left unchanged.
m := map[string]interface{}{
"host": "google.com", // string - convenient
"bar": []byte("foobar"), // byte slice - the fastest
// TagFunc - flexible value. TagFunc is called only if the given
// tag exists in the template.
"query": TagFunc(func(w io.Writer, tag string) (int, error) {
return w.Write([]byte(url.QueryEscape(tag + "=world")))
}),
}
s := ExecuteString(template, "{{", "}}", m)
fmt.Printf("%s", s)
// Output:
// http://google.com/?foo=foobarfoobar&q=query%3Dworld&baz={{baz}}
}
func ExampleTemplateWithSpaces() {
template := "http://{{ host }}/?foo={{ bar }}{{ bar }}&q={{ query }}&baz={{ baz }}"
// Substitution map.
// Since "baz" tag is missing in the map, it will be substituted
// by an empty string.
m := map[string]interface{}{
"host": "google.com", // string - convenient
"bar": []byte("foobar"), // byte slice - the fastest
// TagFunc - flexible value. TagFunc is called only if the given
// tag exists in the template.
"query": TagFunc(func(w io.Writer, tag string) (int, error) {
return w.Write([]byte(url.QueryEscape(tag + "=world")))
}),
}
s := ExecuteString(template, "{{", "}}", m)
fmt.Printf("%s", s)
// Output:
// http://google.com/?foo=foobarfoobar&q=query%3Dworld&baz={{ baz }}
}
func ExampleTagFunc() {
template := "foo[baz]bar"
bazSlice := [][]byte{[]byte("123"), []byte("456"), []byte("789")}
m := map[string]interface{}{
// Always wrap the function into TagFunc.
//
// "baz" tag function writes bazSlice contents into w.
"baz": TagFunc(func(w io.Writer, tag string) (int, error) {
var nn int
for _, x := range bazSlice {
n, err := w.Write(x)
if err != nil {
return nn, err
}
nn += n
}
return nn, nil
}),
}
s := ExecuteString(template, "[", "]", m)
fmt.Printf("%s", s)
// Output:
// foo123456789bar
}