validator

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: May 21, 2024 License: BSD-3-Clause Imports: 8 Imported by: 0

README

Fiber Validator Middleware

Go Version Go Reference Go Report Card

This is a custom validator middleware for the Fiber web framework. It provides a flexible and extensible way to define and apply validation rules to incoming request bodies. The middleware allows for easy validation and sanitization of data, enforcement of specific field requirements, and ensures the integrity of the application's input.

Features

The middleware currently supports the following features:

Request Body Validation
  • Validation of request bodies in various formats, including JSON, XML, and other content types
  • Customizable error handling based on content type
Unicode Restriction
  • Restriction of Unicode characters in specified fields
Conditional Validation
  • Conditional validation skipping based on custom logic
Number Restriction
  • Restriction of fields to contain only numbers with an optional maximum value
String Length Restriction
  • Restriction of string length for specified fields with a configurable maximum length
Advanced Use Cases
  • Storing validation results in the request context for advanced use cases

More features and validation capabilities will be added in the future to enhance the middleware's functionality and cater to a wider range of validation scenarios.

Benchmark

goos: windows
goarch: amd64
pkg: github.com/H0llyW00dzZ/FiberValidator
cpu: AMD Ryzen 9 3900X 12-Core Processor            
BenchmarkValidatorWithSonicJSON/Valid_JSON_request-24         	   45967	     24768 ns/op	   16464 B/op	      86 allocs/op
BenchmarkValidatorWithStandardJSON/Valid_JSON_request-24      	   43248	     27835 ns/op	   16624 B/op	     112 allocs/op
BenchmarkValidatorWithDefaultXML/Valid_XML_request-24         	   28101	     42913 ns/op	   23223 B/op	     212 allocs/op
BenchmarkValidatorWithCustomXML/Valid_XML_request-24          	   28191	     43596 ns/op	   23248 B/op	     212 allocs/op
Updated:
goos: windows
goarch: amd64
pkg: github.com/H0llyW00dzZ/FiberValidator
cpu: AMD Ryzen 9 3900X 12-Core Processor            
BenchmarkValidatorWithSonicJSONSeafood/Valid_JSON_request-24         	   46785	     24696 ns/op	   16447 B/op	      86 allocs/op
BenchmarkValidatorWithStandardJSONSeafood/Valid_JSON_request-24      	   42541	     28542 ns/op	   16672 B/op	     112 allocs/op
BenchmarkValidatorWithDefaultXMLSeafood/Valid_XML_request-24         	   26637	     44806 ns/op	   23450 B/op	     213 allocs/op
BenchmarkValidatorWithCustomXMLSeafood/Valid_XML_request-24          	   26622	     45684 ns/op	   23458 B/op	     213 allocs/op
BenchmarkValidatorWithSonicJSON/Valid_JSON_request-24                	   50625	     24377 ns/op	   16410 B/op	      86 allocs/op
BenchmarkValidatorWithStandardJSON/Valid_JSON_request-24             	   42150	     27954 ns/op	   16626 B/op	     112 allocs/op
BenchmarkValidatorWithDefaultXML/Valid_XML_request-24                	   27764	     43721 ns/op	   23244 B/op	     212 allocs/op
BenchmarkValidatorWithCustomXML/Valid_XML_request-24                 	   27417	     43951 ns/op	   23256 B/op	     212 allocs/op
goos: windows
goarch: amd64
pkg: github.com/H0llyW00dzZ/FiberValidator
cpu: AMD Ryzen 9 3900X 12-Core Processor            
BenchmarkRestrictStringLengthLongDescriptionSonicJSON/Valid_JSON_long_description-24         	   55225	     23263 ns/op	   19344 B/op	      58 allocs/op
BenchmarkRestrictStringLengthLongDescriptionStandardJSON/Valid_JSON_long_description-24      	   48288	     24452 ns/op	   19234 B/op	      65 allocs/op
BenchmarkRestrictStringLengthLongDescriptionDefaultXML/Valid_XML_long_description-24         	   30114	     39411 ns/op	   25018 B/op	     111 allocs/op
BenchmarkRestrictStringLengthLongDescriptionCustomXML/Valid_XML_long_description-24          	   30322	     40180 ns/op	   25025 B/op	     111 allocs/op
BenchmarkValidatorWithSonicJSONSeafood/Valid_JSON_request-24                                 	   51158	     23802 ns/op	   16421 B/op	      86 allocs/op
BenchmarkValidatorWithStandardJSONSeafood/Valid_JSON_request-24                              	   43411	     27269 ns/op	   16652 B/op	     112 allocs/op
BenchmarkValidatorWithDefaultXMLSeafood/Valid_XML_request-24                                 	   26984	     45736 ns/op	   23451 B/op	     213 allocs/op
BenchmarkValidatorWithCustomXMLSeafood/Valid_XML_request-24                                  	   26899	     45503 ns/op	   23443 B/op	     213 allocs/op
BenchmarkValidatorWithSonicJSON/Valid_JSON_request-24                                        	   50936	     24697 ns/op	   16417 B/op	      86 allocs/op
BenchmarkValidatorWithStandardJSON/Valid_JSON_request-24                                     	   43172	     28678 ns/op	   16627 B/op	     112 allocs/op
BenchmarkValidatorWithDefaultXML/Valid_XML_request-24                                        	   27283	     43998 ns/op	   23262 B/op	     212 allocs/op
BenchmarkValidatorWithCustomXML/Valid_XML_request-24                                         	   27990	     43546 ns/op	   23264 B/op	     212 allocs/op
goos: windows
goarch: amd64
pkg: github.com/H0llyW00dzZ/FiberValidator
cpu: AMD Ryzen 9 3900X 12-Core Processor            
BenchmarkRestrictStringLengthLongDescriptionSonicJSON/Valid_JSON_long_description-24         	   51478	     21306 ns/op	   19331 B/op	      58 allocs/op
BenchmarkRestrictStringLengthLongDescriptionStandardJSON/Valid_JSON_long_description-24      	   47730	     25044 ns/op	   19240 B/op	      65 allocs/op
BenchmarkRestrictStringLengthLongDescriptionDefaultXML/Valid_XML_long_description-24         	   30450	     39450 ns/op	   25025 B/op	     111 allocs/op
BenchmarkRestrictStringLengthLongDescriptionCustomXML/Valid_XML_long_description-24          	   29910	     40017 ns/op	   25025 B/op	     111 allocs/op
BenchmarkValidatorWithSonicJSONSeafood/Valid_JSON_request-24                                 	   60594	     20457 ns/op	   14826 B/op	      68 allocs/op
BenchmarkValidatorWithStandardJSONSeafood/Valid_JSON_request-24                              	   50836	     23481 ns/op	   15081 B/op	      94 allocs/op
BenchmarkValidatorWithDefaultXMLSeafood/Valid_XML_request-24                                 	   30085	     40004 ns/op	   21815 B/op	     195 allocs/op
BenchmarkValidatorWithCustomXMLSeafood/Valid_XML_request-24                                  	   29608	     40108 ns/op	   21819 B/op	     195 allocs/op
BenchmarkValidatorWithSonicJSON/Valid_JSON_request-24                                        	   61047	     20826 ns/op	   14801 B/op	      68 allocs/op
BenchmarkValidatorWithStandardJSON/Valid_JSON_request-24                                     	   51811	     23220 ns/op	   15045 B/op	      94 allocs/op
BenchmarkValidatorWithDefaultXML/Valid_XML_request-24                                        	   31850	     38777 ns/op	   21632 B/op	     194 allocs/op
BenchmarkValidatorWithCustomXML/Valid_XML_request-24                                         	   30577	     39133 ns/op	   21633 B/op	     194 allocs/op

[!NOTE] Based on the benchmark results, the following observations can be made:

  • The Sonic JSON encoder/decoder consistently outperforms the standard JSON encoder/decoder in terms of execution time, bytes allocated, and allocations per operation.
  • The custom XML encoder/decoder performs slightly slower than the default XML encoder/decoder in most cases, with similar memory usage.
  • The JSON benchmarks generally have better performance compared to the XML benchmarks, with lower execution time, bytes allocated, and allocations per operation.

gopher run

Overall, the benchmarks using the Sonic JSON encoder/decoder demonstrate the best performance among the tested scenarios.

Contributing

Contributions are welcome! If there are any issues or suggestions for improvements, please open an issue or submit a pull request.

License

This project is licensed under the BSD License. See the LICENSE file for details.

Documentation

Overview

Package validator provides a custom validator middleware for the Fiber web framework. It allows for flexible and extensible validation of incoming request bodies.

Installation

To use this middleware in a Fiber project, Go must be installed and set up.

1. Install the package using Go modules:

go get github.com/H0llyW00dzZ/FiberValidator

2. Import the package in the Fiber application:

import "github.com/H0llyW00dzZ/FiberValidator"

Usage

To use the validator middleware in a Fiber application, create a new instance of the middleware with the desired configuration and register it with the application.

package main

import (
	"github.com/gofiber/fiber/v2"
	"github.com/H0llyW00dzZ/FiberValidator"
)

func main() {
	app := fiber.New()

	app.Use(validator.New(validator.Config{
		Rules: []validator.Restrictor{
			validator.RestrictUnicode{
				Fields: []string{"name", "email"},
			},
		},
	}))

	// Register routes and start the server
	// ...

	app.Listen(":3000")
}

In the example above, a new instance of the validator middleware is created with a configuration that restricts the use of Unicode characters in the "name" and "email" fields of the request body.

Configuration

The validator middleware accepts a validator.Config struct for configuration. The available options are:

  • Rules: A slice of validator.Restrictor implementations that define the validation rules to be applied.
  • Next: An optional function that determines whether to skip the validation middleware for a given request. If the function returns true, the middleware will be skipped.
  • ErrorHandler: An optional custom error handler function that handles the error response. If not provided, the default error handler will be used.

Custom Validation Rules

To define custom validation rules, implement the validator.Restrictor interface:

type Restrictor interface {
	Restrict(c *fiber.Ctx) error
}

The Restrict method takes a Fiber context and returns an error if the validation fails.

Here's an example implementation that restricts the use of Unicode characters in specified fields:

type RestrictUnicode struct {
	Fields []string
}

func (r RestrictUnicode) Restrict(c *fiber.Ctx) error {
	// Parse the request body based on the Content-Type header
	// ...

	// Check each configured field for Unicode characters
	// ...

	return nil
}

Error Handling

The validator middleware provides a default error handler that formats the error response based on the content type of the request. It supports JSON, XML, and plain text formats.

  • For JSON requests, the error response is formatted as {"error": "Error message"}.
  • For XML requests, the error response is formatted as <xmlError><error>Error message</error></xmlError>.
  • For other content types, the error response is sent as plain text.

You can customize the error handling behavior by providing a custom error handler function in the ErrorHandler field of the validator.Config struct. The custom error handler should have the following signature:

func(c *fiber.Ctx, err error) error

Example custom error handler:

func customErrorHandler(c *fiber.Ctx, err error) error {
	if e, ok := err.(*validator.Error); ok {
		return c.Status(fiber.StatusUnprocessableEntity).JSON(fiber.Map{
			"custom_error": e.Message,
		})
	}
	return err
}

In this example, the custom error handler checks if the error is of type *validator.Error and returns a JSON response with a custom error format.

Index

Constants

View Source
const (
	// ErrInvalidJSONBody represents an error message for an invalid JSON request body.
	ErrInvalidJSONBody = "Invalid JSON request body"

	// ErrUnicodeNotAllowedInField represents an error message for Unicode characters not allowed in a specific field.
	ErrUnicodeNotAllowedInField = "Unicode characters are not allowed in the '%s' field"

	// ErrInvalidXMLBody represents an error message for an invalid XML request body.
	ErrInvalidXMLBody = "Invalid XML request body"
)
View Source
const (
	// ErrFieldMustContainNumbersOnly represents an error message for a field that must contain only numbers.
	ErrFieldMustContainNumbersOnly = "The '%s' field must contain only numbers"

	// ErrFieldExceedsMaximumValue represents an error message for a field that exceeds the maximum allowed value.
	ErrFieldExceedsMaximumValue = "The '%s' field must not exceed %d"

	// ErrFieldExceedsMaximumDigits represents an error message for a field that exceeds the maximum allowed number of digits.
	ErrFieldExceedsMaximumDigits = "The '%s' field must not exceed %d digits"
)
View Source
const (
	// ErrFieldExceedsMaximumLength represents an error message for a field that exceeds the maximum allowed length.
	ErrFieldExceedsMaximumLength = "The '%s' field must not exceed %d characters"

	// ErrFieldsExceedMaximumLength represents an error message for fields that exceed the maximum allowed length.
	ErrFieldsExceedMaximumLength = "The '%s' fields must not exceed the maximum length"
)

Variables

View Source
var ConfigDefault = Config{
	Rules:        nil,
	Next:         nil,
	ErrorHandler: DefaultErrorHandler,
	ContextKey:   "",
}

ConfigDefault is the default configuration for the Validator middleware.

Functions

func DefaultErrorHandler

func DefaultErrorHandler(c *fiber.Ctx, err error) error

DefaultErrorHandler is the default error handler function.

func New

func New(config ...Config) fiber.Handler

New creates a new Validator middleware with the provided configuration.

Types

type Config

type Config struct {
	// Rules is a slice of Restrictor implementations to be used for validation.
	Rules []Restrictor

	// Next defines a function to skip this middleware when returned true.
	//
	// Optional. Default: nil
	Next func(c *fiber.Ctx) bool

	// ErrorHandler is a function that handles the error response.
	//
	// Optional. Default: DefaultErrorHandler
	ErrorHandler func(c *fiber.Ctx, err error) error

	// ContextKey is the key used to store the validation result in the context.
	//
	// Note: This is most useful in advanced use cases for communicating internal context within the application,
	// especially for securing authentication and authorization.
	//
	// Optional. Default: nil
	ContextKey string
}

Config defines the configuration for the Validator middleware.

type Error

type Error struct {
	Status  int
	Message string
}

Error represents a validation error.

func NewError

func NewError(status int, message string) *Error

NewError creates a new Error instance.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface for Error.

type RestrictNumberOnly added in v0.2.0

type RestrictNumberOnly struct {
	// Fields specifies the fields to check for number-only validation.
	Fields []string

	// Max specifies the maximum allowed value for the fields (optional).
	Max *int

	// MaxDigits specifies the maximum number of digits allowed in the field value (optional).
	MaxDigits *int
}

RestrictNumberOnly is a Restrictor implementation that restricts fields to contain only numbers and allows setting an optional maximum value and maximum number of digits.

func (RestrictNumberOnly) Restrict added in v0.2.0

func (r RestrictNumberOnly) Restrict(c *fiber.Ctx) error

Restrict implements the Restrictor interface for RestrictNumberOnly. It checks the specified fields in the request body for numeric values and maximum limit based on the content type.

type RestrictStringLength added in v0.5.0

type RestrictStringLength struct {
	// Fields specifies the fields to check for string length validation.
	Fields []string

	// MaxLength specifies the maximum allowed length for the fields (optional).
	MaxLength *int
}

RestrictStringLength is a Restrictor implementation that restricts the length of string fields and allows setting an optional maximum length.

func (RestrictStringLength) Restrict added in v0.5.0

func (r RestrictStringLength) Restrict(c *fiber.Ctx) error

Restrict implements the Restrictor interface for RestrictStringLength. It checks the specified fields in the request body for string length based on the content type.

type RestrictUnicode

type RestrictUnicode struct {
	// Fields specifies the fields to check for Unicode characters.
	Fields []string
}

RestrictUnicode is a Restrictor implementation that restricts the use of Unicode characters in specified fields of the request body.

func (RestrictUnicode) Restrict

func (r RestrictUnicode) Restrict(c *fiber.Ctx) error

Restrict implements the Restrictor interface for RestrictUnicode. It checks the specified fields in the request body for Unicode characters based on the content type.

type Restrictor

type Restrictor interface {
	Restrict(c *fiber.Ctx) error
}

Restrictor is an interface for defining custom validation rules.

Jump to

Keyboard shortcuts

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