bind

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package bind parses and validates request input in one call. Each function decodes the request into T, runs validator.ValidateStruct, and on failure writes a structured error response — 400 for malformed input, 422 for validation errors — returning ok=false so the handler can stop with `return nil`.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Body

func Body[T any](c *fiber.Ctx) (T, bool)

Body decodes the request body (JSON/form/multipart, by Content-Type) into T and validates it. On success it returns (value, true). On failure it writes the error response and returns (zero, false).

Example

Body decodes and validates the request body in one call. On a validation failure it writes a 422 with per-field errors and returns ok=false, so the handler stops with `return nil`.

package main

import (
	"fmt"
	"io"
	"net/http/httptest"
	"strings"

	"github.com/gofiber/fiber/v2"
	"github.com/rahmadafandi/fibr/bind"
)

func main() {
	type signupInput struct {
		Email    string `json:"email" validate:"required,email"`
		Password string `json:"password" validate:"required,min=8"`
	}

	app := fiber.New()
	app.Post("/signup", func(c *fiber.Ctx) error {
		in, ok := bind.Body[signupInput](c)
		if !ok {
			return nil // 400/422 already written
		}
		return c.SendString("welcome " + in.Email)
	})

	req := httptest.NewRequest("POST", "/signup", strings.NewReader(`{"email":"bad","password":"x"}`))
	req.Header.Set("Content-Type", "application/json")
	resp, _ := app.Test(req)
	body, _ := io.ReadAll(resp.Body)

	fmt.Println("status:", resp.StatusCode)
	fmt.Println("body:", string(body))
}
Output:
status: 422
body: {"code":422,"message":"validation failed","data":[{"field":"email","tag":"email","value":"bad"},{"field":"password","tag":"min","param":"8","value":"x"}],"status":"error"}

func Params

func Params[T any](c *fiber.Ctx) (T, bool)

Params decodes the route path parameters into T and validates it. See Body.

func Query

func Query[T any](c *fiber.Ctx) (T, bool)

Query decodes the URL query string into T and validates it. See Body.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL