Fix: Prevent panic when validating struct with nil pointer to map field #260
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request addresses a issue within the
gookit/validate
library where attempting to validate a struct containing a nil pointer to a map field results in a runtime panic.Problem:
The library encounters a panic with the error message:
reflect: call of reflect.Value.MapKeys on zero Value
, when it attempts to validate a struct field that is a nil pointer to a map. This occurs due to the invocation ofMapKeys()
without prior validation of thereflect.Value
being both non-nil and valid.Solution:
A safeguard has been implemented to check that the
reflect.Value
is not nil and is valid before any call toMapKeys()
. This modification ensures graceful handling of nil pointer fields, treating them as empty maps, which is the anticipated behavior for such cases in the validation process.Example Reproduction and Fix Verification:
The issue and the effectiveness of the proposed fix can be demonstrated with the following example:
With the implementation of the proposed fix, the
Validate
method now appropriately interprets the nil pointer to the map as an empty map. Consequently, the validation process proceeds without a panic, and the assertion evaluates as intended, reflecting the non-fulfillment of therequired
rule for theMetadata
field due to its nil value.This enhancement not only prevents undesirable application crashes but also aligns the library's behavior with the conventional handling of nil pointers in Go, thereby improving its reliability and usability.