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.16.

  1. go get github.com/flamego/binding

Getting started

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/flamego/binding"
  6. "github.com/flamego/flamego"
  7. )
  8. type address struct {
  9. Street string `json:"street" validate:"required"`
  10. City string `json:"city" validate:"required"`
  11. Planet string `json:"planet" validate:"required"`
  12. Phone string `json:"phone" validate:"required"`
  13. }
  14. type user struct {
  15. FirstName string `json:"first_name" validate:"required"`
  16. LastName string `json:"last_name" validate:"required"`
  17. Age uint8 `json:"age" validate:"gte=0,lte=130"`
  18. Email string `json:"email" validate:"required,email"`
  19. Addresses []*address `json:"addresses" validate:"required,dive,required"`
  20. }
  21. func main() {
  22. f := flamego.Classic()
  23. f.Post("/", binding.JSON(user{}), func(c flamego.Context, form user, errs binding.Errors) {
  24. if len(errs) > 0 {
  25. c.ResponseWriter().WriteHeader(http.StatusBadRequest)
  26. _, _ = c.ResponseWriter().Write([]byte(fmt.Sprintf("Oops! Error occurred: %v", errs[0].Err)))
  27. return
  28. }
  29. fmt.Printf("Name: %s %s\n", form.FirstName, form.LastName)
  30. })
  31. f.Run()
  32. }

Getting help

License

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