diff --git a/caddy/caddyfile/json.go b/caddy/caddyfile/json.go index 20b36bcc..4617ec03 100644 --- a/caddy/caddyfile/json.go +++ b/caddy/caddyfile/json.go @@ -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: - result += " " + val + 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{}: diff --git a/caddy/caddyfile/json_test.go b/caddy/caddyfile/json_test.go index 11e1b1f4..2e5ed445 100644 --- a/caddy/caddyfile/json_test.go +++ b/caddy/caddyfile/json_test.go @@ -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) {