From f935458e3e30a8d9f47f37ad35fe9c546b841fa3 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Thu, 12 Dec 2019 14:30:22 -0700 Subject: cmd: Fix validate command when JSON contains "@id" fields Also, don't run admin server when validating... --- admin.go | 14 ++++++++++++++ caddy.go | 19 ++++++------------- cmd/commandfuncs.go | 2 ++ 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/admin.go b/admin.go index fcbb62e..570d94c 100644 --- a/admin.go +++ b/admin.go @@ -734,6 +734,20 @@ traverseLoop: return nil } +// RemoveMetaFields removes meta fields like "@id" from a JSON message. +func RemoveMetaFields(rawJSON []byte) []byte { + return idRegexp.ReplaceAllFunc(rawJSON, func(in []byte) []byte { + // matches with a comma on both sides (when "@id" property is + // not the first or last in the object) need to keep exactly + // one comma for correct JSON syntax + comma := []byte{','} + if bytes.HasPrefix(in, comma) && bytes.HasSuffix(in, comma) { + return comma + } + return []byte{} + }) +} + // AdminHandler is like http.Handler except ServeHTTP may return an error. // // If any handler encounters an error, it should be returned for proper diff --git a/caddy.go b/caddy.go index 9dcd883..f13540d 100644 --- a/caddy.go +++ b/caddy.go @@ -153,16 +153,7 @@ func changeConfig(method, path string, input []byte, forceReload bool) error { // (an alternate way to do this would be to delete them from // rawCfg as they are indexed, then iterate the index we made // and add them back after encoding as JSON) - newCfg = idRegexp.ReplaceAllFunc(newCfg, func(in []byte) []byte { - // matches with a comma on both sides (when "@id" property is - // not the first or last in the object) need to keep exactly - // one comma for correct JSON syntax - comma := []byte{','} - if bytes.HasPrefix(in, comma) && bytes.HasSuffix(in, comma) { - return comma - } - return []byte{} - }) + newCfg = RemoveMetaFields(newCfg) // load this new config; if it fails, we need to revert to // our old representation of caddy's actual config @@ -295,9 +286,11 @@ func run(newCfg *Config, start bool) error { var err error // start the admin endpoint (and stop any prior one) - err = replaceAdmin(newCfg) - if err != nil { - return fmt.Errorf("starting caddy administration endpoint: %v", err) + if start { + err = replaceAdmin(newCfg) + if err != nil { + return fmt.Errorf("starting caddy administration endpoint: %v", err) + } } if newCfg == nil { diff --git a/cmd/commandfuncs.go b/cmd/commandfuncs.go index 8526372..3cba47a 100644 --- a/cmd/commandfuncs.go +++ b/cmd/commandfuncs.go @@ -465,6 +465,8 @@ func cmdValidateConfig(fl Flags) (int, error) { input = adaptedConfig } + input = caddy.RemoveMetaFields(input) + var cfg *caddy.Config err = json.Unmarshal(input, &cfg) if err != nil { -- cgit v1.2.3