core

package module
v0.0.0-...-9fae4c4 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2019 License: MIT Imports: 32 Imported by: 7

README

Go服务端HTTP框架

  • koa风格的中间件
  • 路由分组,自定义的分组和单个路由的前置和后置处理
  • 流量限制
  • 优雅重启
  • apidoc接口文档

使用

基于core的种子项目

Documentation

Overview

Package core provides a pure handlers (or middlewares) stack so you can perform actions downstream, then filter and manipulate the response upstream.

The handlers stack

A handler is a function that receives a Context (which contains the response writer and the request). It can be registered with Use and has the possibility to break the stream or to continue with the next handler of the stack.

Example of a logger, followed by a security headers setter, followed by a response writer:

// Log
core.Use(func(c *core.Context) {
	// Before the response.
	start := time.Now()

	// Execute the next handler in the stack.
	c.Next()

	// After the response.
	log.Printf(" %s  %s  %s", c.Request.Method, c.Request.URL, time.Since(start))
})

// Secure
core.Use(func(c *core.Context) {
	c.ResponseWriter.Header().Set("X-Frame-Options", "SAMEORIGIN")
	c.ResponseWriter.Header().Set("X-Content-Type-Options", "nosniff")
	c.ResponseWriter.Header().Set("X-XSS-Protection", "1; mode=block")

	// Execute the next handler in the stack.
	c.Next()
})

// Response
core.Use(func(c *core.Context) {
	fmt.Fprint(c.ResponseWriter, "Hello, World!")
})

// Run server
core.Run()

A clearer visualization of this serving flow:

request open
  |— log start
  |——— secure start
  |————— response write
  |——— secure end
  |— log end
request close

When using Run, your app is reachable at http://localhost:8080 by default.

If you need more flexibility, you can make a new handlers stack, which is fully compatible with the net/http.Handler interface:

hs := core.NewHandlersStack()

hs.Use(func(c *core.Context) {
	fmt.Fprint(c.ResponseWriter, "Hello, World!")
})

http.ListenAndServe(":8080", hs)

Flags

These flags are predefined:

-address
	The address to listen and serving on.
	Value is saved in Address.
-production
	Run the server in production environment.
	Some third-party handlers may have different behaviors
	depending on the environment.
	Value is saved in Production.

It's up to you to call

flag.Parse()

in your main function if you want to use them.

Panic recovering

When using Run, your server always recovers from panics, logs the error with stack, and sends a 500 Internal Server Error. If you want to use a custom handler on panic, give one to HandlePanic.

Handlers and helpers

No handlers or helpers are bundled in the core: it does one thing and does it well. That's why you have to import all and only the handlers or helpers you need:

compress
	Clever response compressing
	github.com/HiLittleCat/compress
cors
	Cross-Origin Resource Sharing support
	https://godoc.org/github.com/HiLittleCat/cors
i18n
	Simple internationalization
	https://godoc.org/github.com/HiLittleCat/i18n
log
	Requests logging
	https://godoc.org/github.com/HiLittleCat/log
response
	Readable response helper
	https://godoc.org/github.com/HiLittleCat/response
secure
	Quick security wins
	https://godoc.org/github.com/HiLittleCat/secure
static
	Simple assets serving
	https://godoc.org/github.com/HiLittleCat/static

Index

Constants

View Source
const (
	None               = 0
	IPAny              = 1
	IPv4               = 32 // IPv4 (32 chars)
	IPv6               = 39 // IPv6(39 chars)
	IPv4MappedIPv6     = 45 // IP4-mapped IPv6 (45 chars) , Ex) ::FFFF:129.144.52.38
	IPv4CIDR           = IPv4 + 3
	IPv6CIDR           = IPv6 + 3
	IPv4MappedIPv6CIDR = IPv4MappedIPv6 + 3
)
View Source
const (
	NORMAL = 0
	STRICT = 4
)

NORMAL BenchmarkRegex-8 2000000000 0.24 ns/op STRICT BenchmarkLoop-8 2000000000 0.01 ns/op

View Source
const (
	ONLY_FILENAME       = 0
	ALLOW_RELATIVE_PATH = 1
)

Variables

View Source
var (
	// OpenCommandLine Open command line params.
	OpenCommandLine bool

	// Production allows handlers know whether the server is running in a production environment.
	Production bool

	// Address is the TCP network address on which the server is listening and serving. Default is ":8080".
	Address = ":8080"

	// Timeout is the duration to allow outstanding requests to survive
	// before forcefully terminating them.
	Timeout = 30 * time.Second

	// ListenLimit Limit the number of outstanding requests
	ListenLimit = 5000

	// ReadTimeout Maximum duration for reading the full request (including body); ns|µs|ms|s|m|h
	ReadTimeout = 5 * time.Second

	// WriteTimeout Maximum duration for writing the full response (including body); ns|µs|ms|s|m|h
	WriteTimeout = 10 * time.Second

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, ReadHeaderTimeout is used.
	IdleTimeout time.Duration

	// MultipartMaxmemoryMb Maximum size of memory that can be used when receiving uploaded files
	MultipartMaxmemoryMb int

	// MaxHeaderBytes Max HTTP Herder size, default is 0, no limit
	MaxHeaderBytes = 1 << 20
)

Log core框架日志

View Source
var Routers = create()

Routers create router instance

Functions

func BeforeRun

func BeforeRun(f func())

BeforeRun adds a function that will be triggered just before running the server.

func HandlePanic

func HandlePanic(h RouterHandler)

HandlePanic sets the panic handler of the default handlers stack.

Context.Data["panic"] contains the panic error.

func Run

func Run()

Run starts the server for listening and serving.

func SessionInit

func SessionInit(expire time.Duration, pool *conn.RedisPool, cookie http.Cookie)

SessionInit 初始化并加载session中间件

func SetLog

func SetLog(logPath string, logFileName string)

SetLog 设置logrus日志配置,logPath参数表示记录日志的路径,logFileName表示日志名称前缀

func Use

func Use(h RouterHandler)

Use adds a handler to the default handlers stack.

Types

type BusinessError

type BusinessError struct {
	// contains filtered or unexported fields
}

BusinessError http.StatusInternalServerError

func (*BusinessError) Error

func (e *BusinessError) Error() string

Error get error message

func (*BusinessError) GetErrno

func (e *BusinessError) GetErrno() int

GetErrno get error Errno

func (*BusinessError) GetHTTPCode

func (e *BusinessError) GetHTTPCode() int

GetHTTPCode get error HTTPCode

func (*BusinessError) New

func (e *BusinessError) New(errno int, message string) *BusinessError

New http.StatusInternalServerError

type Context

type Context struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request

	Params   Params                 // Path Value
	Data     map[string]interface{} // Custom Data
	BodyJSON map[string]interface{} // body json data
	// contains filtered or unexported fields
}

Context contains all the data needed during the serving flow, including the standard http.ResponseWriter and *http.Request.

The Data field can be used to pass all kind of data through the handlers stack.

func (*Context) DeleteSession

func (ctx *Context) DeleteSession() error

DeleteSession delete session

func (*Context) Fail

func (ctx *Context) Fail(err error)

Fail Response fail

func (*Context) FreshSession

func (ctx *Context) FreshSession(key string) error

FreshSession set session

func (*Context) GetBodyJSON

func (ctx *Context) GetBodyJSON()

GetBodyJSON return a json from body

func (*Context) GetSession

func (ctx *Context) GetSession() IStore

GetSession get session

func (*Context) GetSid

func (ctx *Context) GetSid() string

GetSid 获取sid

func (*Context) Next

func (ctx *Context) Next()

Next calls the next handler in the stack, but only if the response isn't already written.

func (*Context) Ok

func (ctx *Context) Ok(data interface{})

Ok Response json

func (*Context) Param

func (ctx *Context) Param(key string) string

Param returns the value of the URL param. It is a shortcut for c.Params.ByName(key)

router.GET("/user/:id", func(c *gin.Context) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"
})

func (*Context) Recover

func (ctx *Context) Recover()

Recover recovers form panics. It logs the stack and uses the PanicHandler (or a classic Internal Server Error) to write the response.

Usage:

defer c.Recover()

func (*Context) Redirect

func (ctx *Context) Redirect(url string, code int)

Redirect Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

func (*Context) ResFree

func (ctx *Context) ResFree(data interface{})

ResFree Response json

func (*Context) ResStatus

func (ctx *Context) ResStatus(code int) (int, error)

ResStatus Response status code, use http.StatusText to write the response.

func (*Context) SetSession

func (ctx *Context) SetSession(key string, values map[string]string) error

SetSession set session

func (*Context) Written

func (ctx *Context) Written() bool

Written tells if the response has been written.

func (*Context) ZipHandler

func (ctx *Context) ZipHandler(fileName string, file []byte)

ZipHandler 响应下载文件请求,返回zip文件

type Controller

type Controller struct {
	Validate *Validation
}

Controller 控制器

func (*Controller) Err

func (c *Controller) Err(errno int, message string) error

Err return a controller error

func (*Controller) GetBodyJSON

func (c *Controller) GetBodyJSON(ctx *Context) map[string]interface{}

GetBodyJSON return a json from body

func (*Controller) GetEmail

func (c *Controller) GetEmail(fieldName string, p interface{}) string

GetEmail check is a email

func (*Controller) Int64Range

func (c *Controller) Int64Range(fieldName string, p interface{}, n int64, m int64) int64

Int64Range param must be a integer, and range is [n, m]

func (*Controller) IntMax

func (c *Controller) IntMax(fieldName string, p interface{}, m int) int

IntMax param must be a integer, and range is [,m]

func (*Controller) IntMin

func (c *Controller) IntMin(fieldName string, p interface{}, n int) int

IntMin param must be a integer, and range is [n,]

func (*Controller) IntRange

func (c *Controller) IntRange(fieldName string, p interface{}, n int, m int) int

IntRange param must be a integer, and range is [n, m]

func (*Controller) IntRangeZoom

func (c *Controller) IntRangeZoom(fieldName string, p interface{}, n int, m int, zoom int) int

IntRangeZoom param must be a number, and range is [n, m], tip is zoom.

func (*Controller) RegisterRouter

func (c *Controller) RegisterRouter()

RegisterRouter this controller to the routers

func (*Controller) StrIn

func (c *Controller) StrIn(fieldName string, p interface{}, l ...string) string

StrIn param is a string, the string is in array

func (*Controller) StrLenIn

func (c *Controller) StrLenIn(fieldName string, p interface{}, l ...int) string

StrLenIn param is a string, length is in array

func (*Controller) StrLenRange

func (c *Controller) StrLenRange(fieldName string, p interface{}, n int, m int) string

StrLenRange param is a string, length range is [n,m]

func (*Controller) StrLength

func (c *Controller) StrLength(fieldName string, p interface{}, n int) string

StrLength param is a string, length must be n

type DBError

type DBError struct {
	DBName string
	// contains filtered or unexported fields
}

DBError http.StatusInternalServerError

func (*DBError) Error

func (e *DBError) Error() string

Error get error message

func (*DBError) GetErrno

func (e *DBError) GetErrno() int

GetErrno get error Errno

func (*DBError) GetHTTPCode

func (e *DBError) GetHTTPCode() int

GetHTTPCode get error HTTPCode

func (*DBError) New

func (e *DBError) New(dbName string, message string) *DBError

New DBError.New

type Domain

type Domain struct {
	Regexp *regexp.Regexp
}

Requires a Domain string to be exactly

func ValidDomain

func ValidDomain() Domain

func (Domain) DefaultMessage

func (d Domain) DefaultMessage() string

func (Domain) IsSatisfied

func (d Domain) IsSatisfied(obj interface{}) bool

type Email

type Email struct {
	Match
}

func ValidEmail

func ValidEmail() Email

func (Email) DefaultMessage

func (e Email) DefaultMessage() string

type Engine

type Engine struct {
	RouterGroup
	// contains filtered or unexported fields
}

Engine each group has a router engine

type FilePath

type FilePath struct {
	Mode int
}

Requires an string to be sanitary file path

func ValidFilePath

func ValidFilePath(m int) FilePath

func (FilePath) DefaultMessage

func (f FilePath) DefaultMessage() string

func (FilePath) IsSatisfied

func (f FilePath) IsSatisfied(obj interface{}) bool

type H

type H map[string]interface{}

H is a shortcut for map[string]interface{}

type HandlersStack

type HandlersStack struct {
	Handlers     []RouterHandler // The handlers stack.
	PanicHandler RouterHandler   // The handler called in case of panic. Useful to send custom server error information. Context.Data["panic"] contains the panic error.
}

HandlersStack contains a set of handlers.

func NewHandlersStack

func NewHandlersStack() *HandlersStack

NewHandlersStack returns a new NewHandlersStack.

func (*HandlersStack) HandlePanic

func (hs *HandlersStack) HandlePanic(h RouterHandler)

HandlePanic sets the panic handler of the handlers stack.

Context.Data["panic"] contains the panic error.

func (*HandlersStack) ServeHTTP

func (hs *HandlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP makes a context for the request, sets some good practice default headers and enters the handlers stack.

func (*HandlersStack) Use

func (hs *HandlersStack) Use(h RouterHandler)

Use adds a handler to the handlers stack.

type IController

type IController interface {
	Register()
	Err(int, string) error
}

IController 控制器接口定义

type ICoreError

type ICoreError interface {
	Error() string
	GetHTTPCode() int
	GetErrno() int
}

ICoreError core error interface

type IModel

type IModel interface {
	Err(string, string) error
}

IModel model interface

type IPAddr

type IPAddr struct {
	Vaildtypes []int
}

Requires a string(IP Address) to be within IP Pattern type inclusive.

func ValidIPAddr

func ValidIPAddr(cktypes ...int) IPAddr

Requires an IP Address string to be exactly a given validation type (IPv4, IPv6, IPv4MappedIPv6, IPv4CIDR, IPv6CIDR, IPv4MappedIPv6CIDR OR IPAny)

func (IPAddr) DefaultMessage

func (i IPAddr) DefaultMessage() string

func (IPAddr) IsSatisfied

func (i IPAddr) IsSatisfied(obj interface{}) bool

type IProvider

type IProvider interface {
	Set(rs IStore) error            //设置存储的session
	Get(sid string) (IStore, error) //函数返回sid所代表的Session变量
	Destroy(sid string) error       //函数用来销毁sid对应的Session
	UpExpire()                      //刷新session有效期
}

IProvider 用以表征session管理器底层存储结构

type IRouter

type IRouter interface {
	IRoutes
	Group(string, ...RouterHandler) *RouterGroup
}

IRouter router interface

type IRoutes

IRoutes routes interface

type IService

type IService interface {
	Err(int, string) error
}

IService service interface

type IStore

type IStore interface {
	Set(key, value string) error //设置设置key值
	Get(key string) string       //读取key对应的value
	Delete(key string) error     //删除key
	SessionID() string           //获取sid
}

IStore session操作

type Length

type Length struct {
	N int
}

Length requires an array or string to be exactly a given length.

func ValidLength

func ValidLength(n int) Length

func (Length) DefaultMessage

func (s Length) DefaultMessage() string

func (Length) IsSatisfied

func (s Length) IsSatisfied(obj interface{}) bool

type MacAddr

type MacAddr struct{}

Requires a MAC Address string to be exactly

func ValidMacAddr

func ValidMacAddr() MacAddr

func (MacAddr) DefaultMessage

func (m MacAddr) DefaultMessage() string

func (MacAddr) IsSatisfied

func (m MacAddr) IsSatisfied(obj interface{}) bool

type Match

type Match struct {
	Regexp *regexp.Regexp
}

Match requires a string to match a given regex.

func ValidMatch

func ValidMatch(regex *regexp.Regexp) Match

func (Match) DefaultMessage

func (m Match) DefaultMessage() string

func (Match) IsSatisfied

func (m Match) IsSatisfied(obj interface{}) bool

type Max

type Max struct {
	Max float64
}

func ValidMax

func ValidMax(max int) Max

func ValidMaxFloat

func ValidMaxFloat(max float64) Max

func (Max) DefaultMessage

func (m Max) DefaultMessage() string

func (Max) IsSatisfied

func (m Max) IsSatisfied(obj interface{}) bool

type MaxSize

type MaxSize struct {
	Max int
}

MaxSize requires an array or string to be at most a given length.

func ValidMaxSize

func ValidMaxSize(max int) MaxSize

func (MaxSize) DefaultMessage

func (m MaxSize) DefaultMessage() string

func (MaxSize) IsSatisfied

func (m MaxSize) IsSatisfied(obj interface{}) bool

type Min

type Min struct {
	Min float64
}

func ValidMin

func ValidMin(min int) Min

func ValidMinFloat

func ValidMinFloat(min float64) Min

func (Min) DefaultMessage

func (m Min) DefaultMessage() string

func (Min) IsSatisfied

func (m Min) IsSatisfied(obj interface{}) bool

type MinSize

type MinSize struct {
	Min int
}

MinSize requires an array or string to be at least a given length.

func ValidMinSize

func ValidMinSize(min int) MinSize

func (MinSize) DefaultMessage

func (m MinSize) DefaultMessage() string

func (MinSize) IsSatisfied

func (m MinSize) IsSatisfied(obj interface{}) bool

type Model

type Model struct {
}

Model model struct

func (*Model) Check

func (m *Model) Check() error

Check 检查model

func (*Model) Err

func (m *Model) Err(errno int, message string) error

Err return a controller error

func (*Model) SetDefault

func (m *Model) SetDefault() error

SetDefault 设置默认值,支持类型string和数字

type NotFoundError

type NotFoundError struct {
	// contains filtered or unexported fields
}

NotFoundError route not found.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error get error message

func (*NotFoundError) GetErrno

func (e *NotFoundError) GetErrno() int

GetErrno get error Errno

func (*NotFoundError) GetHTTPCode

func (e *NotFoundError) GetHTTPCode() int

GetHTTPCode get error HTTPCode

func (*NotFoundError) New

func (e *NotFoundError) New(message string) *NotFoundError

New NotFoundError.New

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByName

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type PureText

type PureText struct {
	Mode int
}

Requires a string to be without invisible characters

func ValidPureText

func ValidPureText(m int) PureText

func (PureText) DefaultMessage

func (p PureText) DefaultMessage() string

func (PureText) IsSatisfied

func (p PureText) IsSatisfied(obj interface{}) bool

type Range

type Range struct {
	Min
	Max
}

Range requires an integer to be within Min, Max inclusive.

func ValidRange

func ValidRange(min, max int) Range

func ValidRangeFloat

func ValidRangeFloat(min, max float64) Range

func (Range) DefaultMessage

func (r Range) DefaultMessage() string

func (Range) IsSatisfied

func (r Range) IsSatisfied(obj interface{}) bool

type Required

type Required struct{}

func ValidRequired

func ValidRequired() Required

func (Required) DefaultMessage

func (r Required) DefaultMessage() string

func (Required) IsSatisfied

func (r Required) IsSatisfied(obj interface{}) bool

type ResFormat

type ResFormat struct {
	Ok      bool        `json:"ok"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
	Errno   int         `json:"errno"`
}

ResFormat response data

type RouterGroup

type RouterGroup struct {
	Handlers RouterHandlerChain
	// contains filtered or unexported fields
}

RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).

func (*RouterGroup) Any

func (group *RouterGroup) Any(relativePath string, handlers ...RouterHandler) IRoutes

Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.

func (*RouterGroup) BasePath

func (group *RouterGroup) BasePath() string

BasePath set group base path

func (*RouterGroup) DELETE

func (group *RouterGroup) DELETE(relativePath string, handlers ...RouterHandler) IRoutes

DELETE is a shortcut for router.Handle("DELETE", path, handle).

func (*RouterGroup) GET

func (group *RouterGroup) GET(relativePath string, handlers ...RouterHandler) IRoutes

GET is a shortcut for router.Handle("GET", path, handle).

func (*RouterGroup) Group

func (group *RouterGroup) Group(relativePath string, handlers ...RouterHandler) *RouterGroup

Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. For example, all the routes that use a common middlware for authorization could be grouped.

func (*RouterGroup) HEAD

func (group *RouterGroup) HEAD(relativePath string, handlers ...RouterHandler) IRoutes

HEAD is a shortcut for router.Handle("HEAD", path, handle).

func (*RouterGroup) Handle

func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...RouterHandler) IRoutes

Handle registers a new request handle and middleware with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. See the example code in github.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*RouterGroup) OPTIONS

func (group *RouterGroup) OPTIONS(relativePath string, handlers ...RouterHandler) IRoutes

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).

func (*RouterGroup) PATCH

func (group *RouterGroup) PATCH(relativePath string, handlers ...RouterHandler) IRoutes

PATCH is a shortcut for router.Handle("PATCH", path, handle).

func (*RouterGroup) POST

func (group *RouterGroup) POST(relativePath string, handlers ...RouterHandler) IRoutes

POST is a shortcut for router.Handle("POST", path, handle).

func (*RouterGroup) PUT

func (group *RouterGroup) PUT(relativePath string, handlers ...RouterHandler) IRoutes

PUT is a shortcut for router.Handle("PUT", path, handle).

func (*RouterGroup) Use

func (group *RouterGroup) Use(middleware ...RouterHandler) IRoutes

Use adds middleware to the group, see example code in github.

type RouterHandler

type RouterHandler func(*Context)

RouterHandler http handler

type RouterHandlerChain

type RouterHandlerChain []RouterHandler

RouterHandlerChain http handler array

type ServerError

type ServerError struct {
	// contains filtered or unexported fields
}

ServerError http.StatusInternalServerError

func (*ServerError) Error

func (e *ServerError) Error() string

Error get error message

func (*ServerError) GetErrno

func (e *ServerError) GetErrno() int

GetErrno get error Errno

func (*ServerError) GetHTTPCode

func (e *ServerError) GetHTTPCode() int

GetHTTPCode get error HTTPCode

func (*ServerError) New

func (e *ServerError) New(message string) *ServerError

New ServerError.New

type Service

type Service struct {
	Validate *Validation
}

Service service struct

type URL

type URL struct {
	Domain
}

func ValidURL

func ValidURL() URL

func (URL) DefaultMessage

func (u URL) DefaultMessage() string

func (URL) IsSatisfied

func (u URL) IsSatisfied(obj interface{}) bool

type Validation

type Validation struct {
}

Validation context manages data validation and error message.

func (*Validation) Domain

func (v *Validation) Domain(str string) bool

func (*Validation) Email

func (v *Validation) Email(str string) bool

func (*Validation) FilePath

func (v *Validation) FilePath(str string, m int) bool

func (*Validation) IPAddr

func (v *Validation) IPAddr(str string, cktype ...int) bool

func (*Validation) Length

func (v *Validation) Length(obj interface{}, n int) bool

func (*Validation) MacAddr

func (v *Validation) MacAddr(str string) bool

func (*Validation) Match

func (v *Validation) Match(str string, regex *regexp.Regexp) bool

func (*Validation) Max

func (v *Validation) Max(n int, max int) bool

func (*Validation) MaxFloat

func (v *Validation) MaxFloat(n float64, max float64) bool

func (*Validation) MaxSize

func (v *Validation) MaxSize(obj interface{}, max int) bool

func (*Validation) Min

func (v *Validation) Min(n int, min int) bool

func (*Validation) MinFloat

func (v *Validation) MinFloat(n float64, min float64) bool

func (*Validation) MinSize

func (v *Validation) MinSize(obj interface{}, min int) bool

func (*Validation) PureText

func (v *Validation) PureText(str string, m int) bool

func (*Validation) Range

func (v *Validation) Range(n, min, max int) bool

func (*Validation) Range64

func (v *Validation) Range64(n, min, max int64) bool

func (*Validation) RangeFloat

func (v *Validation) RangeFloat(n, min, max float64) bool

func (*Validation) Required

func (v *Validation) Required(obj interface{}) bool

Required tests that the argument is non-nil and non-empty (if string or list)

func (*Validation) URL

func (v *Validation) URL(str string) bool

type ValidationError

type ValidationError struct {
	// contains filtered or unexported fields
}

ValidationError simple struct to store the Message & Key of a validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error get error message

func (*ValidationError) GetErrno

func (e *ValidationError) GetErrno() int

GetErrno get error Errno

func (*ValidationError) GetHTTPCode

func (e *ValidationError) GetHTTPCode() int

GetHTTPCode get error HTTPCode

func (*ValidationError) New

func (e *ValidationError) New(message string) *ValidationError

New ValidationError.New

type Validator

type Validator interface {
	IsSatisfied(interface{}) bool
	DefaultMessage() string
}

Directories

Path Synopsis
Package httputil provides HTTP utility functions, complementing the most common ones in package net/http.
Package httputil provides HTTP utility functions, complementing the most common ones in package net/http.
Package log implements a simple logging package for handlers usage.
Package log implements a simple logging package for handlers usage.

Jump to

Keyboard shortcuts

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