Skip to content

Commit

Permalink
cmd: Strict unmarshal for validate (caddyserver#5383)
Browse files Browse the repository at this point in the history
  • Loading branch information
francislavoie authored Feb 22, 2023
1 parent 8bc05e5 commit 79de6df
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 6 deletions.
2 changes: 1 addition & 1 deletion caddy.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
strippedCfgJSON := RemoveMetaFields(cfgJSON)

var newCfg *Config
err := strictUnmarshalJSON(strippedCfgJSON, &newCfg)
err := StrictUnmarshalJSON(strippedCfgJSON, &newCfg)
if err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/commandfuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,7 @@ func cmdAdaptConfig(fl Flags) (int, error) {
// validate output if requested
if adaptCmdValidateFlag {
var cfg *caddy.Config
err = json.Unmarshal(adaptedConfig, &cfg)
err = caddy.StrictUnmarshalJSON(adaptedConfig, &cfg)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
}
Expand Down Expand Up @@ -523,7 +523,7 @@ func cmdValidateConfig(fl Flags) (int, error) {
input = caddy.RemoveMetaFields(input)

var cfg *caddy.Config
err = json.Unmarshal(input, &cfg)
err = caddy.StrictUnmarshalJSON(input, &cfg)
if err != nil {
return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (any, error

// fill in its config only if there is a config to fill in
if len(rawMsg) > 0 {
err := strictUnmarshalJSON(rawMsg, &val)
err := StrictUnmarshalJSON(rawMsg, &val)
if err != nil {
return nil, fmt.Errorf("decoding module config: %s: %v", modInfo, err)
}
Expand Down
4 changes: 2 additions & 2 deletions modules.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,11 +333,11 @@ func ParseStructTag(tag string) (map[string]string, error) {
return results, nil
}

// strictUnmarshalJSON is like json.Unmarshal but returns an error
// StrictUnmarshalJSON is like json.Unmarshal but returns an error
// if any of the fields are unrecognized. Useful when decoding
// module configurations, where you want to be more sure they're
// correct.
func strictUnmarshalJSON(data []byte, v any) error {
func StrictUnmarshalJSON(data []byte, v any) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
return dec.Decode(v)
Expand Down

0 comments on commit 79de6df

Please sign in to comment.