binding

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2023 License: MIT Imports: 9 Imported by: 2

README

binding

GitHub Workflow Status Codecov GoDoc Sourcegraph

Package binding is a middleware that provides request data binding and validation for Flamego.

Installation

The minimum requirement of Go is 1.18.

go get github.com/flamego/binding

Getting started

package main

import (
	"fmt"
	"net/http"

	"github.com/flamego/binding"
	"github.com/flamego/flamego"
)

type address struct {
	Street string `json:"street" validate:"required"`
	City   string `json:"city" validate:"required"`
	Planet string `json:"planet" validate:"required"`
	Phone  string `json:"phone" validate:"required"`
}

type user struct {
	FirstName string     `json:"first_name" validate:"required"`
	LastName  string     `json:"last_name" validate:"required"`
	Age       uint8      `json:"age" validate:"gte=0,lte=130"`
	Email     string     `json:"email" validate:"required,email"`
	Addresses []*address `json:"addresses" validate:"required,dive,required"`
}

func main() {
	f := flamego.Classic()
	f.Post("/", binding.JSON(user{}), func(c flamego.Context, form user, errs binding.Errors) {
		if len(errs) > 0 {
			c.ResponseWriter().WriteHeader(http.StatusBadRequest)
			_, _ = c.ResponseWriter().Write([]byte(fmt.Sprintf("Oops! Error occurred: %v", errs[0].Err)))
			return
		}

		fmt.Printf("Name: %s %s\n", form.FirstName, form.LastName)
	})
	f.Run()
}

Getting help

License

This project is under the MIT License. See the LICENSE file for the full license text.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Form

func Form(model interface{}, opts ...Options) flamego.Handler

Form returns a middleware handler that injects a new instance of the model with populated fields and binding.Errors for any deserialization, binding, or validation errors into the request context. The model instance fields are populated by deserializing the payload from both form-urlencoded data request body and URL query parameters.

func JSON

func JSON(model interface{}, opts ...Options) flamego.Handler

JSON returns a middleware handler that injects a new instance of the model with populated fields and binding.Errors for any deserialization, binding, or validation errors into the request context. The model instance fields are populated by deserializing the JSON payload from the request body.

func MultipartForm

func MultipartForm(model interface{}, opts ...Options) flamego.Handler

MultipartForm returns a middleware handler that injects a new instance of the model with populated fields and binding.Errors for any deserialization, binding, or validation errors into the request context. It works much like binding.Form except it can parse multipart forms and handle file uploads.

func YAML added in v1.1.0

func YAML(model interface{}, opts ...Options) flamego.Handler

YAML returns a middleware handler that injects a new instance of the model with populated fields and binding.Errors for any deserialization, binding, or validation errors into the request context. The model instance fields are populated by deserializing the YAML payload from the request body.

Types

type Error

type Error struct {
	// Category is the type of the error.
	Category ErrorCategory `json:"category,omitempty"`
	// Err is the underlying error.
	Err error `json:"error,omitempty"`
}

Error is an error with a category.

type ErrorCategory

type ErrorCategory string

ErrorCategory represents the type of an error.

const (
	ErrorCategoryDeserialization ErrorCategory = "deserialization"
	ErrorCategoryValidation      ErrorCategory = "validation"
)

type Errors

type Errors []Error

Errors may be generated during deserialization, binding, or validation. This type is mapped to the context so you can inject it into your own handlers and use it in your application if you want all your errors to look the same.

type Options

type Options struct {
	// ErrorHandler will be invoked automatically when errors occurred. Default is
	// to do nothing, but handlers may still use binding.Errors and do custom errors
	// handling.
	ErrorHandler flamego.Handler
	// Validator sets a custom validator instead of the default validator.
	Validator *validator.Validate
	// MaxMemory specifies the maximum amount of memory to be allowed when parsing a
	// multipart form. Default is 10 MiB.
	MaxMemory int64
}

Options contains options for binding.JSON, binding.Form middleware.

Jump to

Keyboard shortcuts

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