Documentation
¶
Overview ¶
Package echo implements high performance, minimalist Go web framework.
Example:
package main
import (
"net/http"
"github.com/adverax/echo"
"github.com/adverax/echo/middleware"
)
// Handler
func hello(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}
func main() {
// Echo instance
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
router := e.Router()
e.GET(router, "/", hello)
// Start server
e.Logger.Error(e.Start(":1323"))
}
Index ¶
- Constants
- Variables
- func DataSetKeys(ctx Context, ds DataSet) ([]string, error)
- func IsPrimitiveDataSet(dataset DataSet) bool
- func MakeModelParams(raw map[string]string) map[string][]string
- func MakeMultiModelName(key, name string) string
- func RenderString(ctx Context, v interface{}) (string, error)
- func RenderWidget(ctx Context, v interface{}) (interface{}, error)
- type BaseFormatter
- type BaseLocale
- func (loc *BaseLocale) DataSet(ctx stdContext.Context, id uint32) (ds DataSet, err error)
- func (loc *BaseLocale) FormatDate(t time.Time) string
- func (loc *BaseLocale) FormatDateTime(t time.Time) string
- func (loc *BaseLocale) FormatTime(t time.Time) string
- func (loc *BaseLocale) Language() uint16
- func (loc *BaseLocale) Location() *time.Location
- func (loc *BaseLocale) Message(ctx stdContext.Context, id uint32) (msg string, err error)
- func (loc *BaseLocale) Now() time.Time
- func (loc *BaseLocale) ParseDate(value string) (time.Time, error)
- func (loc *BaseLocale) ParseDateTime(value string) (time.Time, error)
- func (loc *BaseLocale) ParseTime(value string) (time.Time, error)
- func (loc *BaseLocale) Resource(ctx stdContext.Context, id uint32) (msg string, err error)
- func (loc *BaseLocale) Timezone() uint16
- type Cause
- type Codec
- type Context
- type Converter
- type DATASET
- type DataSet
- type DataSetConsumer
- type DataSetEnumerator
- type DataSetFamily
- type DataSetManager
- type DataSetProvider
- type DataSets
- func (datasets DataSets) DataSet(ctx Context) (DataSet, error)
- func (datasets DataSets) Decode(ctx Context, value interface{}) (string, error)
- func (datasets DataSets) Empty(ctx Context) (interface{}, error)
- func (datasets DataSets) Encode(ctx Context, value string) (interface{}, error)
- func (datasets DataSets) Enumerate(ctx Context, action DataSetConsumer) error
- func (datasets DataSets) Length(ctx Context) (int, error)
- type Decoder
- type DefaultDataSetFamily
- type DefaultDataSetManager
- type DefaultMessageFamily
- type DefaultMessageManager
- type DefaultResourceFamily
- type DefaultResourceManager
- type DefaultUrlLinker
- type DictMapper
- type Echo
- func (e *Echo) AcquireContext() Context
- func (e *Echo) Close() error
- func (e *Echo) DefaultHTTPErrorHandler(c Context, err error)
- func (e *Echo) Dynamic(w http.ResponseWriter, r *http.Request, next http.Handler)
- func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context
- func (e *Echo) NewRouter() Router
- func (e *Echo) ReleaseContext(c Context)
- func (e *Echo) Router() Router
- func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (e *Echo) Shutdown(ctx stdContext.Context) error
- func (e *Echo) Start(address string) error
- func (e *Echo) StartAutoTLS(address string) error
- func (e *Echo) StartServer(s *http.Server) (err error)
- func (e *Echo) StartTLS(address string, certFile, keyFile interface{}) (err error)
- type Encoder
- type Flash
- type FlashClass
- type Float32
- func (codec *Float32) Decode(ctx Context, value interface{}) (string, error)
- func (codec *Float32) Empty(ctx Context) (interface{}, error)
- func (codec *Float32) Encode(ctx Context, value string) (interface{}, error)
- func (codec *Float32) Format(ctx Context, value interface{}) (val interface{}, err error)
- type Float64
- func (codec *Float64) Decode(ctx Context, value interface{}) (string, error)
- func (codec *Float64) Empty(ctx Context) (interface{}, error)
- func (codec *Float64) Encode(ctx Context, value string) (interface{}, error)
- func (codec *Float64) Format(ctx Context, value interface{}) (val interface{}, err error)
- type Formatter
- type HTTPError
- type HTTPErrorHandler
- type Handler
- type HandlerFunc
- type Int
- type Int16
- type Int32
- type Int64
- type Int8
- type ListMapper
- type Locale
- type Map
- type Mapper
- type MapperFunc
- type MessageFamily
- type MessageManager
- type Model
- func (model Model) Bind(ctx Context) error
- func (model Model) BindFrom(ctx Context, data map[string][]string) error
- func (model Model) Clone() Model
- func (model Model) Export(ctx Context, dst interface{}, mapper Mapper) error
- func (model Model) Import(ctx Context, src interface{}, mapper Mapper) error
- func (model Model) IsValid() bool
- func (model Model) Render(ctx Context) (interface{}, error)
- func (model Model) Resolve(ctx Context, src interface{}, dst interface{}, mapper Mapper) error
- type ModelField
- type Models
- type OptionalFormatter
- type Pair
- type PairConverter
- type Pairs
- type RawPair
- type RawPairs
- type ResourceFamily
- type ResourceManager
- type Response
- type Router
- type Session
- type Storage
- type String
- func (codec *String) Decode(ctx Context, value interface{}) (string, error)
- func (codec *String) Empty(ctx Context) (interface{}, error)
- func (codec *String) Encode(ctx Context, value string) (interface{}, error)
- func (codec *String) Format(ctx Context, value interface{}) (val interface{}, err error)
- type Stringer
- type Template
- type Uint
- type Uint16
- func (codec *Uint16) Decode(ctx Context, value interface{}) (string, error)
- func (codec *Uint16) Empty(ctx Context) (interface{}, error)
- func (codec *Uint16) Encode(ctx Context, value string) (interface{}, error)
- func (codec *Uint16) Format(ctx Context, value interface{}) (val interface{}, err error)
- type Uint32
- func (codec *Uint32) Decode(ctx Context, value interface{}) (string, error)
- func (codec *Uint32) Empty(ctx Context) (interface{}, error)
- func (codec *Uint32) Encode(ctx Context, value string) (interface{}, error)
- func (codec *Uint32) Format(ctx Context, value interface{}) (val interface{}, err error)
- type Uint64
- func (codec *Uint64) Decode(ctx Context, value interface{}) (string, error)
- func (codec *Uint64) Empty(ctx Context) (interface{}, error)
- func (codec *Uint64) Encode(ctx Context, value string) (interface{}, error)
- func (codec *Uint64) Format(ctx Context, value interface{}) (val interface{}, err error)
- type Uint8
- type UrlLinker
- type ValidationError
- type ValidationErrors
- type ValidatorFloat32
- type ValidatorFloat32Func
- type ValidatorFloat64
- type ValidatorFloat64Func
- type ValidatorFunc
- type ValidatorInt
- type ValidatorInt16
- type ValidatorInt16Func
- type ValidatorInt32
- type ValidatorInt32Func
- type ValidatorInt64
- type ValidatorInt64Func
- type ValidatorInt8
- type ValidatorInt8Func
- type ValidatorIntFunc
- type ValidatorString
- type ValidatorStringFunc
- type ValidatorUint
- type ValidatorUint16
- type ValidatorUint16Func
- type ValidatorUint32
- type ValidatorUint32Func
- type ValidatorUint64
- type ValidatorUint64Func
- type ValidatorUint8
- type ValidatorUint8Func
- type ValidatorUintFunc
- type Widget
Constants ¶
const ( CONNECT = http.MethodConnect DELETE = http.MethodDelete GET = http.MethodGet HEAD = http.MethodHead OPTIONS = http.MethodOptions PATCH = http.MethodPatch POST = http.MethodPost // PROPFIND = "PROPFIND" PUT = http.MethodPut TRACE = http.MethodTrace )
HTTP methods NOTE: Deprecated, please use the stdlib constants directly instead.
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8 MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
MIME types
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-IP" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" // Access control HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" // Security HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderXCSRFToken = "X-CSRF-Token" )
Headers
const (
ContextKey = contextType(1)
)
const (
// PROPFIND Method can be used on collection and property resources.
PROPFIND = "PROPFIND"
)
const (
// Version of Echo
Version = "5.0.0"
)
Variables ¶
var ( StringCodec = new(String) IntCodec = new(Int) Int8Codec = new(Int8) Int16Codec = new(Int16) Int32Codec = new(Int32) Int64Codec = new(Int64) UintCodec = new(Uint) Uint8Codec = new(Uint8) Uint16Codec = new(Uint16) Uint32Codec = new(Uint32) Uint64Codec = new(Uint64) Float32Codec = new(Float32) Float64Codec = new(Float64) BoolCodec Codec = new(Uint) // Override in real application OptionalIntFormatter = &OptionalFormatter{Formatter: IntCodec} OptionalInt8Formatter = &OptionalFormatter{Formatter: Int8Codec} OptionalInt16Formatter = &OptionalFormatter{Formatter: Int16Codec} OptionalInt32Formatter = &OptionalFormatter{Formatter: Int32Codec} OptionalInt64Formatter = &OptionalFormatter{Formatter: Int64Codec} OptionalUintFormatter = &OptionalFormatter{Formatter: UintCodec} OptionalUint8Formatter = &OptionalFormatter{Formatter: Uint8Codec} OptionalUint16Formatter = &OptionalFormatter{Formatter: Uint16Codec} OptionalUint32Formatter = &OptionalFormatter{Formatter: Uint32Codec} OptionalUint64Formatter = &OptionalFormatter{Formatter: Uint64Codec} OptionalFloat32Formatter = &OptionalFormatter{Formatter: Float32Codec} OptionalFloat64Formatter = &OptionalFormatter{Formatter: Float64Codec} )
var ( MessageInvalidValue uint32 = 1 MessageRequiredValue uint32 = 2 MessageMustBeNotBelow uint32 = 3 MessageMustBeNotAbove uint32 = 4 ValidationErrorInvalidValue = NewValidationError(MessageInvalidValue) ValidationErrorRequiredValue = NewValidationError(MessageRequiredValue) )
var ( ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType) ErrNotFound = NewHTTPError(http.StatusNotFound) ErrForbidden = NewHTTPError(http.StatusForbidden) ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed) ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge) ErrTooManyRequests = NewHTTPError(http.StatusTooManyRequests) ErrBadRequest = NewHTTPError(http.StatusBadRequest) ErrBadGateway = NewHTTPError(http.StatusBadGateway) ErrInternalServerError = NewHTTPError(http.StatusInternalServerError) ErrRequestTimeout = NewHTTPError(http.StatusRequestTimeout) ErrValidatorNotRegistered = errors.New("validator not registered") ErrRendererNotRegistered = errors.New("renderer not registered") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrCookieNotFound = errors.New("cookie not found") ErrInvalidCertOrKeyType = errors.New("invalid cert or key type, must be string or []byte") ErrAbort = errors.New("abort") ErrModelSealed = errors.New("model is accepted") )
Errors
var ( NotFoundHandler = func(c Context) error { return ErrNotFound } MethodNotAllowedHandler = func(c Context) error { return ErrMethodNotAllowed } )
Error handlers
var ( DefaultMapper = MapperFunc(func(name string) (string, bool) { return strings.Title(name), true }) DefaultMessages = make(DefaultMessageFamily) DefaultResources = make(DefaultResourceFamily) DefaultDataSets = make(DefaultDataSetFamily) Defaults = struct { Messages MessageManager Resources ResourceManager DataSets DataSetManager UrlLinker UrlLinker Cache cache.Cache Cacher cacher.Cacher Arbiter arbiter.Arbiter Locale Locale MessageManager MessageManager ResourceManager ResourceManager DataSetManager DataSetManager }{ UrlLinker: &DefaultUrlLinker{}, Arbiter: arbiter.NewLocal(), Cache: memory.New(memory.Options{}), Messages: &DefaultMessageManager{ family: DefaultMessages, }, Resources: &DefaultResourceManager{ family: DefaultResources, }, DataSets: &DefaultDataSetManager{ family: DefaultDataSets, }, Locale: &BaseLocale{ DateFormat: generic.DateFormat, TimeFormat: generic.TimeFormat, DateTimeFormat: generic.DateTimeFormat, Lang: 1, TZone: 1, Loc: time.UTC, Messages: DefaultMessages, Resources: DefaultResources, DataSets: DefaultDataSets, }, } )
var EmptySet = NewDataSet(make(map[string]string), false)
Functions ¶
func DataSetKeys ¶
DataSetKeys returns list of all keys of dataset
func IsPrimitiveDataSet ¶
func MakeModelParams ¶
Create model parameters from map.
func MakeMultiModelName ¶
Create name of field of band
func RenderString ¶
func RenderWidget ¶
Types ¶
type BaseFormatter ¶
type BaseFormatter struct {
Decoder
}
Formatter, that based on codec.Decode method
func (*BaseFormatter) Format ¶
func (w *BaseFormatter) Format( ctx Context, value interface{}, ) (interface{}, error)
type BaseLocale ¶
type BaseLocale struct {
DateFormat string
TimeFormat string
DateTimeFormat string
Lang uint16 // Language identifier
TZone uint16 // Timezone identifier
Loc *time.Location
Messages MessageFamily
Resources ResourceFamily
DataSets DataSetFamily
}
BaseLocale is a simple Locale structure.
func (*BaseLocale) DataSet ¶
func (loc *BaseLocale) DataSet(ctx stdContext.Context, id uint32) (ds DataSet, err error)
func (*BaseLocale) FormatDate ¶
func (loc *BaseLocale) FormatDate(t time.Time) string
func (*BaseLocale) FormatDateTime ¶
func (loc *BaseLocale) FormatDateTime(t time.Time) string
func (*BaseLocale) FormatTime ¶
func (loc *BaseLocale) FormatTime(t time.Time) string
func (*BaseLocale) Language ¶
func (loc *BaseLocale) Language() uint16
func (*BaseLocale) Location ¶
func (loc *BaseLocale) Location() *time.Location
func (*BaseLocale) Message ¶
func (loc *BaseLocale) Message(ctx stdContext.Context, id uint32) (msg string, err error)
func (*BaseLocale) Now ¶
func (loc *BaseLocale) Now() time.Time
func (*BaseLocale) ParseDateTime ¶
func (loc *BaseLocale) ParseDateTime(value string) (time.Time, error)
func (*BaseLocale) Resource ¶
func (loc *BaseLocale) Resource(ctx stdContext.Context, id uint32) (msg string, err error)
func (*BaseLocale) Timezone ¶
func (loc *BaseLocale) Timezone() uint16
type Cause ¶
type Cause struct {
Msg uint32 // Identifier of message
Text string // Default literal representation
Args []interface{} // Custom arguments
}
Complex validation error
type Codec ¶
type Codec interface {
Encoder
Decoder
// Get internal empty value
Empty(ctx Context) (interface{}, error)
}
Coder and Decoder
type Context ¶
type Context interface {
stdContext.Context
// Request returns `*http.Request`.
Request() *http.Request
// SetRequest sets `*http.Request`.
SetRequest(r *http.Request)
// Response returns `*Response`.
Response() *Response
// IsTLS returns true if HTTP connection is TLS otherwise false.
IsTLS() bool
// IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
IsWebSocket() bool
// Scheme returns the HTTP protocol scheme, `http` or `https`.
Scheme() string
// RealIP returns the client's network address based on `X-Forwarded-For`
// or `X-Real-IP` request header.
RealIP() string
// Param returns path parameter by name.
Param(name string) string
ParamString(name string, defaults string) string
ParamInt(name string, defaults int) int
ParamInt8(name string, defaults int8) int8
ParamInt16(name string, defaults int16) int16
ParamInt32(name string, defaults int32) int32
ParamInt64(name string, defaults int64) int64
ParamUint(name string, defaults uint) uint
ParamUint8(name string, defaults uint8) uint8
ParamUint16(name string, defaults uint16) uint16
ParamUint32(name string, defaults uint32) uint32
ParamUint64(name string, defaults uint64) uint64
ParamFloat32(name string, defaults float32) float32
ParamFloat64(name string, defaults float64) float64
ParamBoolean(name string, defaults bool) bool
// ParamNames returns path parameter names.
ParamNames() []string
// SetParamNames sets path parameter names.
SetParamNames(names ...string)
// ParamValues returns path parameter values.
ParamValues() []string
// SetParamValues sets path parameter values.
SetParamValues(values ...string)
// QueryParam returns the query param for the provided name.
QueryParam(name string) string
// QueryParams returns the query parameters as `url.Values`.
QueryParams() url.Values
// QueryString returns the URL query string.
QueryString() string
// FormValue returns the form field value for the provided name.
FormValue(name string) string
// FormParams returns the form parameters as `url.Values`.
FormParams() (url.Values, error)
// FormFile returns the multipart form file for the provided name.
FormFile(name string) (*multipart.FileHeader, error)
// MultipartForm returns the multipart form.
MultipartForm() (*multipart.Form, error)
// Cookie returns the named cookie provided in the request.
Cookie(name string) (*http.Cookie, error)
// SetCookie adds a `Set-Cookie` header in HTTP response.
SetCookie(cookie *http.Cookie)
// Cookies returns the HTTP cookies sent with the request.
Cookies() []*http.Cookie
// Get retrieves data from the context.
Get(key interface{}) interface{}
// Set saves data in the context.
Set(key interface{}, val interface{})
// Create new context with new value.
WithValue(key interface{}, val interface{}) Context
// HTML sends an HTTP response with status code.
HTML(code int, html string) error
// HTMLBlob sends an HTTP blob response with status code.
HTMLBlob(code int, b []byte) error
// String sends a string response with status code.
String(code int, s string) error
// JSON sends a JSON response with status code.
JSON(code int, i interface{}) error
// JSONPretty sends a pretty-print JSON with status code.
JSONPretty(code int, i interface{}, indent string) error
// JSONBlob sends a JSON blob response with status code.
JSONBlob(code int, b []byte) error
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
JSONP(code int, callback string, i interface{}) error
// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
// to construct the JSONP payload.
JSONPBlob(code int, callback string, b []byte) error
// XML sends an XML response with status code.
XML(code int, i interface{}) error
// XMLPretty sends a pretty-print XML with status code.
XMLPretty(code int, i interface{}, indent string) error
// XMLBlob sends an XML blob response with status code.
XMLBlob(code int, b []byte) error
// Blob sends a blob response with status code and content type.
Blob(code int, contentType string, b []byte) error
// Stream sends a streaming response with status code and content type.
Stream(code int, contentType string, r io.Reader) error
// Template sends a HTML response with status code,
Template(code int, t Template, data interface{}) (err error)
// File sends a response with the content of the file.
File(file string) error
// Attachment sends a response as attachment, prompting client to save the
// file.
Attachment(file string, name string) error
// Inline sends a response as inline, opening the file in the browser.
Inline(file string, name string) error
// NoContent sends a response with no body and a status code.
NoContent(code int) error
// Redirect redirects the request to a provided URL with status code.
Redirect(code int, url string) error
// Refresh redirects the request to the corrent URL with status code.
Refresh(code int) error
// Revert redirects the request to a prev (referrer URL) address with status code.
Revert(code int) error
// Error invokes the registered HTTP error handler. Generally used by middleware.
Error(err error)
// Handler returns the matched handler by router.
Handler() HandlerFunc
// SetHandler sets the matched handler by router.
SetHandler(h HandlerFunc)
// Logger returns the `Logger` instance.
Logger() log.Logger
// Session returns the `Session` instance.
Session() Session
// SetSession sets the `Session` instance.
SetSession(session Session)
// Echo returns the `Echo` instance.
Echo() *Echo
// Reset resets the context after request completes. It must be called along
// with `Echo#AcquireContext()` and `Echo#ReleaseContext()`.
// See `Echo#ServeHTTP()`
Reset(r *http.Request, w http.ResponseWriter)
// Get active locale
Locale() Locale
// Set active locale
SetLocale(locale Locale)
// Add flash message
AddFlash(class FlashClass, message interface{}) error
}
Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.
func RequestContext ¶
type DataSet ¶
type DataSet interface {
Codec
DataSetEnumerator
DataSetProvider
}
Abstract data set Works with literal representation keys and values.
func NewDataSet ¶
Create new DataSet from map
func NewDataSetFromList ¶
Create new DataSet from list.
func NewDataSetFromSequence ¶
Create new DataSet from sequence of key/val pairs.
func ParseDataSet ¶
Create DataSource from literal representation DATA SET FORMAT: The source may have a headline or not. In the absence of a headline, a list is implied. Each element is located on a separate line. Each line can end with a comment, that starts from "#".
HEADLINE The title must begin with "#!". The header consists of attributes (with or without values), separated by spaces. Valid attributes:
- SORTED - items must be sorted
- DELIMITER - separator for maps (between key and value). Default - ":".
Example: #! MAP SORTED DELIMITER ::
ITEM FORMAT Each element has a format: key: value or just a value. The numbering of elements starts from one (used only if the key is omitted). The next item is max + 1. Blank lines (or "_" lines) have code, but are not displayed. Empty characters at the beginning and end of the line are ignored.
type DataSetConsumer ¶
type DataSetEnumerator ¶
type DataSetEnumerator interface {
// Get items count
Length(ctx Context) (int, error)
// Enumerate all items
Enumerate(ctx Context, consumer DataSetConsumer) error
}
DataSet enumerator
type DataSetFamily ¶
type DataSetFamily interface {
Fetch(ctx stdContext.Context, id uint32) (DataSet, error)
}
DataSetFamily for active language
type DataSetManager ¶
type DataSetProvider ¶
DataSet provider
type DataSets ¶
Map of DataSet by language code.
type DefaultDataSetFamily ¶
func (DefaultDataSetFamily) Fetch ¶
func (family DefaultDataSetFamily) Fetch( ctx stdContext.Context, id uint32, ) (DataSet, error)
type DefaultDataSetManager ¶
type DefaultDataSetManager struct {
// contains filtered or unexported fields
}
func (*DefaultDataSetManager) Find ¶
func (manager *DefaultDataSetManager) Find(ctx stdContext.Context, doc uint32, lang uint16) (DataSet, error)
func (*DefaultDataSetManager) FindAll ¶
func (manager *DefaultDataSetManager) FindAll(ctx stdContext.Context, doc uint32) (DataSets, error)
type DefaultMessageFamily ¶
func (DefaultMessageFamily) Fetch ¶
func (messages DefaultMessageFamily) Fetch( ctx stdContext.Context, id uint32, ) (string, error)
type DefaultMessageManager ¶
type DefaultMessageManager struct {
// contains filtered or unexported fields
}
func (*DefaultMessageManager) Find ¶
func (manager *DefaultMessageManager) Find(ctx stdContext.Context, id uint32, lang uint16) (string, error)
type DefaultResourceFamily ¶
func (DefaultResourceFamily) Fetch ¶
func (messages DefaultResourceFamily) Fetch( ctx stdContext.Context, id uint32, ) (string, error)
type DefaultResourceManager ¶
type DefaultResourceManager struct {
// contains filtered or unexported fields
}
func (*DefaultResourceManager) Find ¶
func (manager *DefaultResourceManager) Find(ctx stdContext.Context, id uint32, lang uint16) (string, error)
type DefaultUrlLinker ¶
type DefaultUrlLinker struct{}
func (*DefaultUrlLinker) Collapse ¶
func (linker *DefaultUrlLinker) Collapse(ctx Context, url string) string
type DictMapper ¶
type Echo ¶
type Echo struct {
Server *http.Server
TLSServer *http.Server
Listener net.Listener
TLSListener net.Listener
AutoTLSManager autocert.Manager
DisableHTTP2 bool
Debug bool
HideBanner bool
HidePort bool
Complex bool
HTTPErrorHandler HTTPErrorHandler
Logger log.Logger
Locale Locale // Prototype
UrlLinker UrlLinker
Cache cache.Cache
Cacher cacher.Cacher
Messages MessageManager
Resources ResourceManager
DataSets DataSetManager
Arbiter arbiter.Arbiter
// contains filtered or unexported fields
}
Echo is the top-level framework instance.
func (*Echo) AcquireContext ¶
AcquireContext returns an empty `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.
func (*Echo) DefaultHTTPErrorHandler ¶
DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response with status code.
func (*Echo) Dynamic ¶
Dynamic is internal method, that used for init context for handling dynamic HTTP requests in the COMPLEX mode.
func (*Echo) NewContext ¶
NewContext returns a Context instance.
func (*Echo) ReleaseContext ¶
ReleaseContext returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.
func (*Echo) ServeHTTP ¶
func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (*Echo) Shutdown ¶
func (e *Echo) Shutdown(ctx stdContext.Context) error
Shutdown stops the server gracefully. It internally calls `http.Server#Shutdown()`.
func (*Echo) StartAutoTLS ¶
StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.
func (*Echo) StartServer ¶
StartServer starts a custom http server.
type Flash ¶
type Flash struct {
Class FlashClass
Message interface{}
}
type FlashClass ¶
type FlashClass string
Flash notification
const ( FlashError FlashClass = "danger" FlashWarning FlashClass = "warning" FlashSuccess FlashClass = "success" FlashInfo FlashClass = "info" )
type Float32 ¶
type Float32 struct {
Min float32
Max float32
Validator ValidatorFloat32
}
Float32 value
type Float64 ¶
type Float64 struct {
Min float64
Max float64
Validator ValidatorFloat64
}
Float64 value
type HTTPError ¶
type HTTPError struct {
Code int
Message interface{}
Internal error // Stores the error returned by an external dependency
}
HTTPError represents an error that occurred while handling a request.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError instance.
func (*HTTPError) SetInternal ¶
SetInternal sets error to HTTPError.Internal
type HTTPErrorHandler ¶
HTTPErrorHandler is a centralized HTTP error handler.
type HandlerFunc ¶
HandlerFunc defines a function to serve HTTP requests.
func WrapHandler ¶
func WrapHandler(h http.Handler) HandlerFunc
WrapHandler wraps `http.Handler` into `echo.HandlerFunc`.
func (HandlerFunc) ServeHTTP ¶
func (fn HandlerFunc) ServeHTTP(ctx Context) error
type ListMapper ¶
type ListMapper []string
type Locale ¶
type Locale interface {
// Format date at the current location
FormatDate(t time.Time) string
// Format time at the current location
FormatTime(t time.Time) string
// Format datetime at the current location
FormatDateTime(t time.Time) string
// Parse date at the current location
ParseDate(value string) (time.Time, error)
// Parse time at the current location
ParseTime(value string) (time.Time, error)
// Parse datetime at the current location
ParseDateTime(value string) (time.Time, error)
// Get active language identifier
Language() uint16
// Get active timezone identifier
Timezone() uint16
// Get active location
Location() *time.Location
// Get message translation into the current language
Message(ctx stdContext.Context, id uint32) (string, error)
// Get resource translation into the current language
Resource(ctx stdContext.Context, id uint32) (string, error)
// Get data source translation into the current language
DataSet(ctx stdContext.Context, id uint32) (DataSet, error)
// Get current time in the location
Now() time.Time
}
Locale represents localization strategy.
type Map ¶
type Map map[string]interface{}
Map defines a generic map of type `map[string]interface{}`.
type Mapper ¶
type Mapper interface {
// Convert external representation to internal representation
Execute(name string) (string, bool)
}
Mapper is abstract converter external field names into internal model field names.
type MapperFunc ¶
type MessageFamily ¶
type MessageFamily interface {
Fetch(ctx stdContext.Context, id uint32) (string, error)
}
MessageFamily for active language
type MessageManager ¶
type Model ¶
type Model map[string]interface{}
func (Model) Export ¶
Export exports model data into external structure. External field names can be composite structure. For such fields need mapper, that defien dotted path to the target field.
type ModelField ¶
type ModelField interface {
// Field has no errors
IsValid() bool
// Get list of validation errors
GetErrors() ValidationErrors
// Get name of field
GetName() string
// Get internal representation of value
GetVal() interface{}
// Set internal representation of value
SetVal(ctx Context, value interface{})
// Get external representation of value
GetValue() []string
// Set external representation of value
SetValue(ctx Context, value []string) error
// Validate field and extends field errors
Validate(ctx Context) error
// Get internal data as signed value
GetInt() int
// Get internal data as signed value
GetInt8() int8
// Get internal data as signed value
GetInt16() int16
// Get internal data as signed value
GetInt32() int32
// Get internal data as signed value
GetInt64() int64
// Get internal data as unsigned value
GetUint() uint
// Get internal data as unsigned value
GetUint8() uint8
// Get internal data as unsigned value
GetUint16() uint16
// Get internal data as unsigned value
GetUint32() uint32
// Get internal data as unsigned value
GetUint64() uint64
// Get internal data as decimal value
GetFloat32() float32
// Get internal data as decimal value
GetFloat64() float64
// Get internal data as string value
GetString() string
// Get internal data as boolean value
GetBoolean() bool
// Get flag disabled
GetDisabled() bool
// Get flag hidden
GetHidden() bool
// Delete all errors and uncheck field and set default value
Reset(ctx Context) error
}
Abstract field. Implemented by descendants of field.
type OptionalFormatter ¶
type OptionalFormatter struct {
Formatter
}
OptionalFormatter is formatter for any optional value. OptionalFormatter is wrapper for inner formatter. Example:
formatter := &OptionalFormatter{
Formatter: &Signed{},
}
func (*OptionalFormatter) Format ¶
func (formatter *OptionalFormatter) Format(ctx Context, value interface{}) (val interface{}, err error)
type PairConverter ¶
type PairConverter interface {
Formatter
// contains filtered or unexported methods
}
func NewCustomPairConverter ¶
func NewCustomPairConverter(codec DataSet, formatter Formatter) PairConverter
func NewPairConverter ¶
func NewPairConverter(codec DataSet) PairConverter
type RawPair ¶
type RawPair struct {
Key string
Val interface{}
}
RawPair supports transformation values from interfaces into the strings.
type ResourceFamily ¶
type ResourceFamily interface {
Fetch(ctx stdContext.Context, id uint32) (string, error)
}
ResourceFamily for active language
type ResourceManager ¶
type Response ¶
type Response struct {
Writer http.ResponseWriter
Status int
Size int64
Committed bool
// contains filtered or unexported fields
}
Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See: https://golang.org/pkg/net/http/#ResponseWriter
func NewResponse ¶
func NewResponse(w http.ResponseWriter, e *Echo) (r *Response)
NewResponse creates a new instance of Response.
func (*Response) After ¶
func (r *Response) After(fn func())
After registers a function which is called just after the response is written. If the `Content-Length` is unknown, none of the after function is executed.
func (*Response) Before ¶
func (r *Response) Before(fn func())
Before registers a function which is called just before the response is written.
func (*Response) Flush ¶
func (r *Response) Flush()
Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)
func (*Response) Header ¶
Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
func (*Response) Hijack ¶
Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)
func (*Response) WriteHeader ¶
WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.
type Router ¶
type Router interface {
http.Handler
chi.Routes
// Use appends one of more middlewares onto the Router stack.
Use(middlewares ...func(http.Handler) http.Handler)
// With adds inline middlewares for an endpoint handler.
With(middlewares ...func(http.Handler) http.Handler) Router
// Group adds a new inline-Router along the current routing
// path, with a fresh middleware stack for the inline-Router.
Group(fn func(r Router)) Router
// Route mounts a sub-Router along a `pattern“ string.
Route(pattern string, fn func(r Router)) Router
// Mount attaches another http.Handler along ./pattern/*
Mount(pattern string, h HandlerFunc)
// Handle and HandleFunc adds routes for `pattern` that matches
// all HTTP methods.
Handle(pattern string, h HandlerFunc)
// Method and MethodFunc adds routes for `pattern` that matches
// the `method` HTTP method.
Method(method, pattern string, h HandlerFunc)
// HTTP-method routing along `pattern`
Connect(pattern string, h HandlerFunc)
Delete(pattern string, h HandlerFunc)
Get(pattern string, h HandlerFunc)
Head(pattern string, h HandlerFunc)
Options(pattern string, h HandlerFunc)
Patch(pattern string, h HandlerFunc)
Post(pattern string, h HandlerFunc)
Put(pattern string, h HandlerFunc)
Trace(pattern string, h HandlerFunc)
Form(pattern string, h HandlerFunc)
// NotFound defines a handler to respond whenever a route could
// not be found.
NotFound(h HandlerFunc)
// MethodNotAllowed defines a handler to respond whenever a method is
// not allowed.
MethodNotAllowed(h HandlerFunc)
}
type Session ¶
type Session interface {
Storage
// Clear deletes all values in the session.
Clear()
// AddFlash adds a flash message to the session.
AddFlash(class FlashClass, message interface{})
// Flashes returns a slice of flash messages from the session.
Flashes() []*Flash
// Save saves all sessions used during the current request.
Save(ctx Context) error
}
Abstract interface for session
type Storage ¶
type Storage interface {
// Get value by key.
Get(key string, dst interface{}) error
// Set value with key and expire time.
Set(key string, val interface{}, timeout time.Duration) error
// Check if value exists or not.
IsExists(key string) (bool, error)
// Delete cached value by key.
Delete(key string) error
}
Abstract data storage
type UrlLinker ¶
type UrlLinker interface {
// Render url
Render(ctx Context, url *url.URL) (string, error)
// Expand url by current shard
Expand(ctx Context, url string) string
// Collapse url by removing current shard
Collapse(ctx Context, url string) string
}
Url manager (linker)
type ValidationError ¶
Validation error can be translated into target language.
func NewValidationError ¶
func NewValidationError(id uint32) ValidationError
func NewValidationErrorMustBeNotAbove ¶
func NewValidationErrorMustBeNotAbove( limit string, ) ValidationError
func NewValidationErrorMustBeNotBelow ¶
func NewValidationErrorMustBeNotBelow( limit string, ) ValidationError
func NewValidationErrorString ¶
func NewValidationErrorString(msg string) ValidationError
type ValidationErrors ¶
type ValidationErrors []ValidationError
List of validation errors Can be used as error
func AppendValidationError ¶
func AppendValidationError( errs ValidationErrors, err error, ) (ValidationErrors, error)
func (ValidationErrors) Error ¶
func (errs ValidationErrors) Error() string
type ValidatorFloat32 ¶
type ValidatorFloat32Func ¶
type ValidatorFloat64 ¶
type ValidatorFloat64Func ¶
type ValidatorFunc ¶
type ValidatorFunc func() error