-
Notifications
You must be signed in to change notification settings - Fork 5
/
strategy.go
60 lines (50 loc) · 1.04 KB
/
strategy.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
package main
import (
"bytes"
"fmt"
"os"
"text/template"
)
type PrintStrategy interface {
Print() error
}
type ConsoleStrategy struct{}
type FileStrategy struct {
DestinationFilePath string
}
func (c *ConsoleStrategy) BuildOutput() string {
return "ConsoleStrategy"
}
func (c *ConsoleStrategy) Print() error {
fmt.Println(c.BuildOutput())
lister, _ := template.New("foo").Parse(tplTemplate())
lister.Execute(os.Stdout, tplParams())
return nil
}
func (c *FileStrategy) Print() error {
fmt.Println("FileStrategy")
var t bytes.Buffer
foo, _ := template.New("bar").Parse(tplTemplate())
foo.Execute(&t, tplParams())
f, err := os.Create(c.DestinationFilePath)
if err != nil {
panic(err)
}
defer f.Close()
f.Write(t.Bytes())
return nil
}
func tplParams() map[string]interface{} {
items := []int{1, 1, 2, 3, 5, 8}
return map[string]interface{}{
"items": items,
"last": len(items) - 1,
}
}
func tplTemplate() string {
return "" +
"{{range $i, $el := .items}}" +
"{{$el}}" +
"{{if eq $i $.last}}.{{else}}, {{end}}" +
"{{end}}"
}