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 ¶
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"}
Types ¶
This section is empty.