Commit 976f5182 authored by Matthew Holt's avatar Matthew Holt

caddyfile: Better string and number handling

parent 0f19df8a
......@@ -25,7 +25,7 @@ func ToJSON(caddyfile []byte) ([]byte, error) {
block := ServerBlock{Body: make(map[string]interface{})}
for _, host := range sb.HostList() {
block.Hosts = append(block.Hosts, host)
block.Hosts = append(block.Hosts, strings.TrimSuffix(host, ":"))
}
for dir, tokens := range sb.Tokens {
......@@ -107,7 +107,7 @@ func FromJSON(jsonBytes []byte) ([]byte, error) {
if i > 0 {
result += ", "
}
result += host
result += strings.TrimSuffix(host, ":")
}
result += jsonToText(sb.Body, 1)
}
......@@ -122,11 +122,15 @@ func jsonToText(scope interface{}, depth int) string {
switch val := scope.(type) {
case string:
if strings.ContainsAny(val, "\" \n\t\r") {
result += ` "` + strings.Replace(val, "\"", "\\\"", -1) + `"`
} else {
result += " " + val
}
case int:
result += " " + strconv.Itoa(val)
case float64:
result += " " + fmt.Sprintf("%f", val)
result += " " + fmt.Sprintf("%v", val)
case bool:
result += " " + fmt.Sprintf("%t", val)
case map[string]interface{}:
......
......@@ -6,26 +6,26 @@ var tests = []struct {
caddyfile, json string
}{
{ // 0
caddyfile: `foo: {
caddyfile: `foo {
root /bar
}`,
json: `[{"hosts":["foo:"],"body":{"root":["/bar"]}}]`,
json: `[{"hosts":["foo"],"body":{"root":["/bar"]}}]`,
},
{ // 1
caddyfile: `host1:, host2: {
caddyfile: `host1, host2 {
dir {
def
}
}`,
json: `[{"hosts":["host1:","host2:"],"body":{"dir":[{"def":null}]}}]`,
json: `[{"hosts":["host1","host2"],"body":{"dir":[{"def":null}]}}]`,
},
{ // 2
caddyfile: `host1:, host2: {
caddyfile: `host1, host2 {
dir abc {
def ghi
}
}`,
json: `[{"hosts":["host1:","host2:"],"body":{"dir":["abc",{"def":["ghi"]}]}}]`,
json: `[{"hosts":["host1","host2"],"body":{"dir":["abc",{"def":["ghi"]}]}}]`,
},
{ // 3
caddyfile: `host1:1234, host2:5678 {
......@@ -34,6 +34,31 @@ var tests = []struct {
}`,
json: `[{"hosts":["host1:1234","host2:5678"],"body":{"dir":["abc",{}]}}]`,
},
{ // 4
caddyfile: `host {
foo "bar baz"
}`,
json: `[{"hosts":["host"],"body":{"foo":["bar baz"]}}]`,
},
{ // 5
caddyfile: `host, host:80 {
foo "bar \"baz\""
}`,
json: `[{"hosts":["host","host:80"],"body":{"foo":["bar \"baz\""]}}]`,
},
{ // 6
caddyfile: `host {
foo "bar
baz"
}`,
json: `[{"hosts":["host"],"body":{"foo":["bar\nbaz"]}}]`,
},
{ // 7
caddyfile: `host {
dir 123 4.56 true
}`,
json: `[{"hosts":["host"],"body":{"dir":["123","4.56","true"]}}]`, // NOTE: I guess we assume numbers and booleans should be encoded as strings...?
},
}
func TestToJSON(t *testing.T) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment