validator

package module
Version: v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2020 License: MIT Imports: 14 Imported by: 0

README

Validator

Build Status

Validator is a http request parameters checker.

Installation

Make sure that Go is installed on your computer. Type the following command in your terminal:

$ go get github.com/VictorCPH/validator

Import package in your project

Add following line in your *.go file:

import "github.com/VictorCPH/validator"

Usage

Basic
// examples/basic/main.go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/VictorCPH/validator"
)

type param struct {
	Name      string    `form:"name" json:"name" valid:"required" regexp:"^[a-zA-Z_][a-zA-Z_]*$"`
	Age       int       `form:"age" json:"age" valid:"required" range:"18|25"`
	Passed    bool      `form:"passed" json:"passed" valid:"required"`
	Score     float32   `form:"score" json:"score" valid:"required" min:"60.0"`
	Area      float64   `form:"area" json:"area" valid:"required" max:"200.0"`
	Side      string    `form:"side" json:"side" valid:"required" values:"front|back"`
	Friends   []string  `form:"friends" json:"friends" valid:"required" regexp:"^[a-zA-Z_][a-zA-Z_]*$"`
	Scores    []float32 `form:"scores" json:"scores" valid:"required" range:"60|100"`
	ExtraInfo string    `form:"extra_info" json:"extra_info" valid:"optional" default:"hello"`
}

func handler(w http.ResponseWriter, r *http.Request) {
	obj := param{}
	err := validator.Bind(r, &obj)
	if err != nil {
		json.NewEncoder(w).Encode(map[string]string{"msg": err.Error()})
	} else {
		json.NewEncoder(w).Encode(obj)
	}
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("Listening on port: 8080")
	http.ListenAndServe(":8080", nil)
}
# run examples/basic/main.go and visit localhost:8080
$ go run examples/basic/main.go

Test it with form:

$ curl -v -XPOST "localhost:8080" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "name=ming" \
  -d "age=20" \
  -d "passed=true" \
  -d "score=86.5" \
  -d "area=148.898877383" \
  -d "side=front" \
  -d "friends[]=Mary" -d "friends[]=Jack" \
  -d "scores[]=68.5" -d "scores[]=73.5"

Test it with query string:

$ curl -v -g -XGET "localhost:8080/?name=ming&age=20&passed=true&score=86.5&area=148.898877383&side=front&friends[]=Mary&friends[]=Jack&scores[]=68.5&scores[]=73.5"

Test it with json:

$ curl -v -XPOST "localhost:8080" \
  -H "Content-Type: application/json" \
  -d '{"name":"ming","age":20,"passed":true,"score":86.5,"area":148.898877383,"side":"front","friends":["Mary","Jack"],"scores":[68.5,73.5],"extra_info":"hello"}'
Multipart file
// examples/file_bind/main.go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/VictorCPH/validator"
)

type fileParam struct {
	Image []byte `form:"image" valid:"required" type:"file" max_size:"61440"`
	Name  string `form:"name" valid:"required" regexp:"^[a-zA-Z_][a-zA-Z_]*$"`
}

func handler(w http.ResponseWriter, r *http.Request) {
	obj := fileParam{}
	err := validator.Bind(r, &obj)
	if err != nil {
		json.NewEncoder(w).Encode(map[string]string{"msg": err.Error()})
	} else {
		json.NewEncoder(w).Encode(map[string]int{"image_size": len(obj.Image)})
	}
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("Listening on port: 8080")
	http.ListenAndServe(":8080", nil)
}
# run examples/file_bind/main.go and visit localhost:8080
$ go run examples/file_bind/main.go

Test it with:

$ curl -v -XPOST "localhost:8080" \
  -F "image=@testdata/Go-Logo_Aqua.jpg" \
  -F "name=ming"
Base64 string
// examples/base64_bind/main.go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/VictorCPH/validator"
)

type base64Param struct {
	Label []byte `form:"label" valid:"required" type:"base64"`
}

func handler(w http.ResponseWriter, r *http.Request) {
	obj := base64Param{}
	err := validator.Bind(r, &obj)
	if err != nil {
		json.NewEncoder(w).Encode(map[string]string{"msg": err.Error()})
	} else {
		json.NewEncoder(w).Encode(map[string]string{"label": string(obj.Label)})
	}
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("Listening on port: 8080")
	http.ListenAndServe(":8080", nil)
}
# run examples/base64_bind/main.go and visit localhost:8080
$ go run examples/base64_bind/main.go

Test it with:

$ curl -v -XPOST "localhost:8080" \
  -d "label=aGVsbG8="

Support tags

form, json, valid, default, type, values, min, max, range, regexp, max_size
  • if use form format, you shold contain a form tag to give the name of the field.
  • if use json format, you shold contain a json tag to give the name of the field.
  • every param validation should contain a valid tag, it must be required or optional.
  • default tag can only be used with optional.
  • values tag can only be used with int float32 float64 bool string.
  • min, max, range tag can only be used with int, float32, float64.
  • regexp tag can only be used with string.
  • type tag now only support file and base64.
  • if type:"file", it will read file as []byte.
  • if type:"base64", it will read base64 string, then decode it and save as []byte.
  • max_size tag can only be used with type:"file", it will check the max size of file.

Supported Types:

int, bool, float32, float64, string, slice, []byte

If you has more demands, report an issue, or open up a pull request.

License

The repo is available as open source under the terms of the MIT License.

Documentation

Index

Constants

View Source
const (
	ContentTypeForm      = "application/x-www-form-urlencoded"
	ContentTypeMultipart = "multipart/form-data"
	ContentTypeJson      = "application/json"
)

Content Type

View Source
const (
	// Parse data error
	ERR_EMPTY_CONTENT_TYPE       = "empty Content-Type"
	ERR_UNSUPPORTED_CONTENT_TYPE = "unsupported Content-Type"
	ERR_PARSE_FORM               = "parse form failed"
	ERR_PARSE_MULTIPART_FORM     = "parse multipart form failed"
	ERR_DECODE_JSON              = "decode json failed"

	// Coerce error
	ERR_OPTIONAL_PARAM_NOT_FOUND = "optional param not found"
	ERR_PARAM_NOT_FOUND          = "not found"
	ERR_PARAM_INVALID            = "%s expected"
	ERR_CORRUPTED_FILE           = "corrupted file"
	ERR_PARAM_FILE_NOT_FOUND     = "file not found"
	ERR_FILE_TYPE_INVALID        = "file expected"

	// Validate error
	ERR_PARAM_FILE_TOO_LARGE = "file larger than %d bytes"
	ERR_INVALID_MAX_SIZE_TAG = "invalid `max_size` tag, must be int"
	ERR_INVALID_VALID_TAG    = "invalid `valid` tag, must be `required` or `optional`"
	ERR_INVALID_MAX_TAG      = "invalid `max` tag, must be int or float"
	ERR_INVALID_MIN_TAG      = "invalid `min` tag, must be int or float"
	ERR_INVALID_RANGE_TAG    = "invalid `range` tag, must be (int|int) or (float|float)"
	ERR_INVALID_BASE64       = "invalid base64 string"
	ERR_INVALID_UTF8_STRING  = "invalid utf8 string"
	ERR_GREATER_THAN_MAX     = "greater than %s"
	ERR_SMALLER_THAN_MIN     = "smaller than %s"
	ERR_BLANK_STRING         = "blank string"
	ERR_INVALID_ENUMERATION  = "%s is not in %s"
	ERR_WRONG_FORMAT         = "wrong format, shold match regexp `%s`"
	ERR_NOT_IN_RANGE         = "not in range (%s, %s)"
)

Error Message

View Source
const Version = "v0.2.0"

Version is the current validator's version.

Variables

View Source
var MultipartMemory int64 = 64 * 1024 * 1024

MultipartMemory is the maximum permitted size of the request body in an HTTP request. The whole request body is parsed and up to a total of MultipartMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files.

Functions

func Bind

func Bind(req *http.Request, obj interface{}) error

Bind takes data out of the request and deserializes into a interface obj according to the Content-Type of the request. If no Content-Type is specified, there better be data in the query string, otherwise an error will be produced. A non-nil return value may be an Errors value.

func BindForm

func BindForm(req *http.Request, obj interface{}) error

func BindJson

func BindJson(req *http.Request, obj interface{}) error

func BindMultipart

func BindMultipart(req *http.Request, obj interface{}) error

func BindURL

func BindURL(req *http.Request, obj interface{}) error

Types

This section is empty.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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