Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Prevent panic on validating nil pointer to slice field (#252) #253

Merged
merged 1 commit into from
Jan 3, 2024

Conversation

kaptinlin
Copy link
Contributor

This pull request addresses the panic encountered when the gookit/validate library attempts to validate a struct that contains a nil pointer to a slice field, as reported in issue #252.

Problem:
When validating a struct with a field that is a nil pointer to a slice, the library would panic with an error message: reflect: call of reflect.Value.Len on zero Value. This is due to a call to Len() without first checking if the reflect.Value is valid and not nil.

Solution:
The proposed fix introduces a check that ensures the reflect.Value is valid and not nil before any call to Len(). This prevents the panic by safely handling nil pointers as if they point to empty slices, which aligns with the expected behavior of the validation library.

Example:
The issue can be reproduced and tested with the following example:

package main

import (
    "github.com/gookit/validate"
    "github.com/stretchr/testify/assert"
)

type Data struct {
    PtrStrings *[]string `validate:"strings"`
}

func main() {
    v := validate.New(&Data{})

    ok := v.Validate() // Before the fix, this would panic
    assert.True(t, ok) 
}

With the fix applied, the Validate method now correctly handles the nil pointer by treating it as an empty slice, and the assertion passes without a panic.

@coveralls
Copy link

Pull Request Test Coverage Report for Build 7382742445

  • 0 of 0 changed or added relevant lines in 0 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage decreased (-0.03%) to 96.204%

Totals Coverage Status
Change from base Build 7207994547: -0.03%
Covered Lines: 2864
Relevant Lines: 2977

💛 - Coveralls

@inhere inhere merged commit 117b816 into gookit:master Jan 3, 2024
7 of 11 checks passed
@inhere inhere added the bug Something isn't working label Jan 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants