Thanks to visit codestin.com
Credit goes to github.com

Skip to content

🐛 bug: fix bind struct validation only for struct targets#4082

Merged
ReneWerner87 merged 3 commits intomainfrom
bugfix/bind-struct-validator-map-and-skip-validation-
Feb 11, 2026
Merged

🐛 bug: fix bind struct validation only for struct targets#4082
ReneWerner87 merged 3 commits intomainfrom
bugfix/bind-struct-validator-map-and-skip-validation-

Conversation

@ReneWerner87
Copy link
Member

Based on feedback in discord chat

package main

import (
	"log"
	"strings"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v3"
)

type structValidator struct {
	validate *validator.Validate
}

func (v *structValidator) Validate(out any) error {
	return v.validate.Struct(out)
}

func main() {
	app := fiber.New(
		fiber.Config{
			// when the validator is disabled /test succesfully binds the data and returns a response.
			// with it active, it gives a "nil *map[string]string" error message
			StructValidator: &structValidator{validate: validator.New()},
		},
	)

	app.Get("/", func(c fiber.Ctx) error {
		return c.SendFile("./index.html")
	})

	app.Post("/test", func(c fiber.Ctx) error {
		var req map[string]string

		if err := c.Bind().Form(&req); err != nil { // ERROR - validator: nil *map[string]string
			return fiber.NewError(fiber.StatusBadRequest, err.Error())
		}

		log.Println(req)

		var response strings.Builder

		for submission := range req {
			response.WriteString(" " + submission)
		}

		return c.SendString(response.String())
	})

	app.Listen(":3000")
}

Copilot AI review requested due to automatic review settings February 11, 2026 12:18
@ReneWerner87 ReneWerner87 requested a review from a team as a code owner February 11, 2026 12:18
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ReneWerner87, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses an issue where the StructValidator was incorrectly attempting to validate non-struct types, such as maps, leading to errors. The core change involves modifying the validation mechanism to ensure it only operates on actual struct targets. Additionally, a new SkipValidation option has been added to provide more granular control over when validation should occur, enhancing flexibility for developers.

Highlights

  • Refined Struct Validation Logic: The StructValidator now explicitly checks if the target type is a struct (or a pointer to a struct) before attempting validation, preventing incorrect validation attempts on non-struct types like maps.
  • Added SkipValidation Option: A new SkipValidation method has been introduced to the Bind chain, allowing developers to explicitly enable or disable struct validation for a specific binding operation.
  • Enhanced Test Coverage: New test cases were added to verify that struct validation is correctly skipped for map destinations and that the new SkipValidation option functions as expected.
  • Updated Documentation: The API and guide documentation have been updated to reflect the new SkipValidation method and to clarify that StructValidator only applies to struct targets.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • bind.go
    • Added SkipValidation method to the Bind struct to control validation.
    • Modified validateStruct to only run validation for struct types, unwrapping pointers as needed.
    • Introduced skipValidation field to the Bind struct.
  • bind_test.go
    • Added mapStructValidator to test validation skipping for maps.
    • Implemented Test_Bind_Form_Map_SkipsStructValidator to confirm map binding works without struct validation.
    • Added Test_Bind_SkipValidation to verify the functionality of the new SkipValidation method.
  • docs/api/bind.md
    • Documented the new SkipValidation method.
    • Added a note clarifying that StructValidator only runs for struct destinations.
  • docs/guide/validation.md
    • Added a note to the validation guide explaining that StructValidator applies only to struct destinations.
Activity
  • The changes were based on feedback received in a Discord chat, indicating a response to community input.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@ReneWerner87 ReneWerner87 added this to v3 Feb 11, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 11, 2026

Walkthrough

Adds SkipValidation(skip bool) to Bind and refactors validation to only run when a StructValidator is configured and the destination is a concrete struct (or pointer to struct); maps and other non-struct destinations skip validation. Tests and docs updated.

Changes

Cohort / File(s) Summary
Bind implementation & tests
bind.go, bind_test.go
Added func (b *Bind) SkipValidation(skip bool) *Bind; updated validateStruct to unwrap pointers, skip validation for non-struct destinations, and avoid calling the validator when none is configured; added countingStructValidator and tests covering map binding, skip toggling, JSON, explicit re-enable, and nil-target behavior.
Documentation
docs/api/bind.md, docs/guide/validation.md
Documented SkipValidation() and clarified that StructValidator runs only for struct destinations (or pointers to structs) and is skipped for maps/other non-struct types.
Manifest / deps
manifest_file, go.mod
Dependency/manifest updates included with test and doc additions.

Sequence Diagram(s)

(omitted — changes are localized to binding validation control flow and tests)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

✏️ Feature

Suggested reviewers

  • gaby
  • sixcolors
  • efectn

Poem

I hop through binds with gentle cheer,
Skipping checks where maps appear,
A flick, SkipValidation in paw,
Structs still vetted, rules in awe,
Hooray — the binding runs so clear! 🐇✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description provides a concrete code example demonstrating the bug but lacks structured information following the template, missing details on changes introduced, testing, and documentation updates. Complete the PR description template sections: document the changes introduced, testing/documentation updates, type of change checkboxes, and verification checklist items.
✅ Passed checks (2 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Title check ✅ Passed The PR title mentions the core fix (struct validation only for struct targets) and partially references the secondary feature (SkipValidation option via 🐛 emoji context), aligning with the main changes in the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bugfix/bind-struct-validator-map-and-skip-validation-

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Feb 11, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.98%. Comparing base (8ca5213) to head (a61db01).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4082      +/-   ##
==========================================
- Coverage   90.99%   90.98%   -0.01%     
==========================================
  Files         119      119              
  Lines       11256    11266      +10     
==========================================
+ Hits        10242    10250       +8     
- Misses        642      643       +1     
- Partials      372      373       +1     
Flag Coverage Δ
unittests 90.98% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adjusts Fiber’s binding validation behavior to avoid invoking StructValidator for non-struct bind targets (e.g., maps), and adds a per-bind-chain option to explicitly skip validation when desired. This aligns the implementation with the intended semantics of “struct validation” and prevents validator errors when binding into map destinations.

Changes:

  • Run StructValidator only when the bind destination is a struct (or pointer(s) to a struct).
  • Add (*Bind).SkipValidation(bool) to enable/disable validation for a bind chain.
  • Add tests and documentation clarifying the updated validation behavior and the new option.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
bind.go Adds SkipValidation and gates struct validation to struct destinations only.
bind_test.go Adds coverage ensuring map binds skip validation and SkipValidation works as intended.
docs/guide/validation.md Documents that validation only runs for struct destinations.
docs/api/bind.md Documents the new SkipValidation option and clarifies struct-only validation.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces two valuable changes. First, it fixes a bug where struct validation was incorrectly attempted on non-struct types (like maps), which could lead to a panic. The fix correctly uses reflection to ensure validation is only applied to struct destinations. Second, it adds a new SkipValidation option to the binding chain, providing more control to the developer. The changes are well-implemented, accompanied by thorough tests, and the documentation has been updated accordingly. This is a solid improvement to the binding functionality.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@bind_test.go`:
- Around line 2005-2024: The subtest "toggle on same bind instance" is missing
t.Parallel() which all other subtests use; inside the t.Run anonymous function
(the func(t *testing.T) passed to t.Run for the "toggle on same bind instance"
test) add a call to t.Parallel() as the first statement to enable parallel
execution—ensure it sits before acquiring the context via app.AcquireCtx and
before any shared-state operations involving c, c.Bind().SkipValidation, and
simpleQuery so the subtest runs concurrently like the others.

@gaby gaby changed the title fix: run bind struct validation only for struct targets and add SkipValidation option 🐛 bug: fix bind struct validation only for struct targets Feb 11, 2026
Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, only thing would be adding a code example in the docs using SkipValidation()

@ReneWerner87 ReneWerner87 merged commit cea3dc3 into main Feb 11, 2026
21 of 23 checks passed
@ReneWerner87 ReneWerner87 deleted the bugfix/bind-struct-validator-map-and-skip-validation- branch February 11, 2026 13:43
@github-project-automation github-project-automation bot moved this to Done in v3 Feb 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants