Skip to content

Commit 3de56f0

Browse files
committed
Add "json" function
1 parent e354c96 commit 3de56f0

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

template.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"bytes"
5+
"encoding/json"
56
"errors"
67
"fmt"
78
"io"
@@ -80,6 +81,15 @@ func hashSha1(input string) string {
8081
return fmt.Sprintf("%x", h.Sum(nil))
8182
}
8283

84+
func marshalJson(input interface{}) (string,error) {
85+
var buf bytes.Buffer
86+
enc := json.NewEncoder(&buf)
87+
if err := enc.Encode(input); err != nil {
88+
return "", err
89+
}
90+
return strings.TrimSuffix(buf.String(), "\n"), nil
91+
}
92+
8393
func generateFile(config Config, containers Context) bool {
8494
templatePath := config.Template
8595
tmpl, err := template.New(filepath.Base(templatePath)).Funcs(template.FuncMap{
@@ -91,6 +101,7 @@ func generateFile(config Config, containers Context) bool {
91101
"replace": strings.Replace,
92102
"dict": dict,
93103
"sha1": hashSha1,
104+
"json": marshalJson,
94105
}).ParseFiles(templatePath)
95106
if err != nil {
96107
log.Fatalf("unable to parse template: %s", err)

template_test.go

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package main
22

3-
import "testing"
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"testing"
7+
)
48

59
func TestContains(t *testing.T) {
610
env := map[string]string{
@@ -139,3 +143,43 @@ func TestSha1(t *testing.T) {
139143
t.Fatal("Incorrect SHA1 sum")
140144
}
141145
}
146+
147+
func TestJson(t *testing.T) {
148+
containers := []*RuntimeContainer{
149+
&RuntimeContainer{
150+
Env: map[string]string{
151+
"VIRTUAL_HOST": "demo1.localhost",
152+
},
153+
ID: "1",
154+
},
155+
&RuntimeContainer{
156+
Env: map[string]string{
157+
"VIRTUAL_HOST": "demo1.localhost,demo3.localhost",
158+
},
159+
ID: "2",
160+
},
161+
&RuntimeContainer{
162+
Env: map[string]string{
163+
"VIRTUAL_HOST": "demo2.localhost",
164+
},
165+
ID: "3",
166+
},
167+
}
168+
output, err := marshalJson(containers)
169+
if err != nil {
170+
t.Fatal(err)
171+
}
172+
173+
buf := bytes.NewBufferString(output)
174+
dec := json.NewDecoder(buf)
175+
if err != nil {
176+
t.Fatal(err)
177+
}
178+
var decoded []*RuntimeContainer
179+
if err := dec.Decode(&decoded); err != nil {
180+
t.Fatal(err)
181+
}
182+
if len(decoded) != len(containers) {
183+
t.Fatal("Incorrect unmarshaled container count. Expected %d, got %d.", len(containers), len(decoded))
184+
}
185+
}

0 commit comments

Comments
 (0)