framework

package module
v0.0.0-...-a32ce64 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2018 License: MIT Imports: 39 Imported by: 0

README

AnUnamedFramework written in Golang

Inspired by many web frameworks during the last 20 years of software development.

Parts of this framework are still a work in progress, feel free to open an issue or a pull request.

Documentation

Index

Constants

View Source
const (
	// DebugMode - set the framework in debug mode.
	DebugMode string = "debug"
	// ProductionMode - set the framework in production mode.
	ProductionMode string = "production"
	// TestMode - set the framework in testing mode.
	TestMode string = "test"
)
View Source
const VERSION = "0.5.2"

VERSION of the Framework.

Variables

View Source
var DefaultErrorMessages = map[string]string{
	"Required":     "can not be empty",
	"Min":          "minimum value is %d",
	"MinLength":    "minimum length is %d",
	"Max":          "maximum value is %d",
	"MaxLength":    "maximum length is %d",
	"Exact":        "required value is %d",
	"ExactLength":  "required length is %d",
	"Alpha":        "must contain a valid alpha characters",
	"AlphaNumeric": "must contain a valid alpha numeric characters",
	"Numeric":      "must be a valid numeric value",
	"Float":        "must be a valid float value",
	"URL":          "must be a valid URL",
	"Email":        "must be a valid email address",
	"IP":           "must be a valid ip address",
	"Base64":       "must be a valid base64",
	"String":       "must be a string",
	"Float64":      "must be a float64",
	"Bool":         "must be a bool",
}

DefaultErrorMessages contains the rule's default error messages.

Functions

func AddFunc

func AddFunc(key string, fn interface{})

AddFunc register a func in the view.

func ConcatenateCSS

func ConcatenateCSS(paths []string) []byte

ConcatenateCSS returns concatenated CSS paths to []byte

func DecodeCookie

func DecodeCookie(key []byte, maxlifetime int, signedValue string, req *http.Request) (string, error)

DecodeCookie decrypt and return the cookie id.

func EncodeCookie

func EncodeCookie(key []byte, sessionID string, req *http.Request) string

EncodeCookie return a new encrypted cookie string.

func GetSessionID

func GetSessionID(r *http.Request, name string) string

GetSessionID return the cookie from http request.

func GetTemplateFuncs

func GetTemplateFuncs() template.FuncMap

GetTemplateFuncs returs the FuncMap with framework custom functions.

func MinifyCSS

func MinifyCSS(css []byte) string

MinifyCSS returns the minified CSS string

func MinifyHTML

func MinifyHTML(html []byte) string

MinifyHTML returns a minified HTML version. Removes all HTML comments. Remove all leading and trailing white space of each line. Pad a single space to the line if its length > 0

func MinifyJS

func MinifyJS(js []byte) string

MinifyJS returns a compressed javascript using Google Closure Compiler

func Mode

func Mode() string

Mode retreives the current mode.

func NewSessionID

func NewSessionID() string

NewSessionID return a new random cookie.

func RegisterController

func RegisterController(c Controller)

RegisterController register the specified controller on framework. controller func Init is called on framework initialization.

func RegisterGRPCService

func RegisterGRPCService(s GRPCServices)

RegisterGRPCService registers a new gRPC service. Registered services are called via Init(s *framework.GRPCServer) where you finally register your protos servers before Serving the gRPC.

func RemoveCSSComments

func RemoveCSSComments(content []byte) []byte

RemoveCSSComments returns a CSS comments striped string

func RemoveHTMLComments

func RemoveHTMLComments(content []byte) []byte

RemoveHTMLComments removes the HTML comments from provided []byte, returns a []byte

func Run

func Run()

Run start listening on configured HTTP port.

func RunGRPC

func RunGRPC()

RunGRPC start gRPC listening on configured port.

func RunTLS

func RunTLS()

RunTLS start HTTPS listening on configured port.

func ServerStreamInterceptor

func ServerStreamInterceptor() grpc.StreamServerInterceptor

ServerStreamInterceptor creates a single stream interceptor from a list of interceptors. Use UseGRPCStreamInterceptor to add a new global stream interceptor.

func ServerUnaryInterceptor

func ServerUnaryInterceptor() grpc.UnaryServerInterceptor

ServerUnaryInterceptor creates a single unary interceptor from a list of interceptors. Use UseGRPCUnaryInterceptor to add a new global unary interceptor.

func SetGoogleAnalytics

func SetGoogleAnalytics(code string)

SetGoogleAnalytics sets the google analytics id (UA-XXXXXXX-X) you can get the analytics code on views: {{ template "google_analytics" . }}

func SetMode

func SetMode(value string)

SetMode change the current mode.

func Use

func Use(filter HandlerFunc)

Use appends a new global middleware. Global middlewares are called on each request (including static files)

func UseGRPCStreamInterceptor

func UseGRPCStreamInterceptor(filter grpc.StreamServerInterceptor)

UseGRPCStreamInterceptor appends a new global gRPC stream interceptor.

func UseGRPCUnaryInterceptor

func UseGRPCUnaryInterceptor(filter grpc.UnaryServerInterceptor)

UseGRPCUnaryInterceptor appends a new global gRPC unary interceptor.

Types

type BaseController

type BaseController struct {
	Router   Router
	Layout   string
	Meta     map[string]string
	Response http.ResponseWriter
	Request  *http.Request
}

BaseController implements the Controller. All user defined controllers must use BaseController.

func (*BaseController) Any

func (c *BaseController) Any(pattern string, handlers ...HandlerFunc)

Any register a route that matches all HTTP methods. (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)

func (*BaseController) DELETE

func (c *BaseController) DELETE(pattern string, handlers ...HandlerFunc)

DELETE is an alias to Add(pattern, "DELETE", handlers)

func (*BaseController) GET

func (c *BaseController) GET(pattern string, handlers ...HandlerFunc)

GET is an alias to Add(pattern, "GET", handlers)

func (*BaseController) HEAD

func (c *BaseController) HEAD(pattern string, handlers ...HandlerFunc)

HEAD is an alias to Add(pattern, "HEAD", handlers)

func (*BaseController) OPTIONS

func (c *BaseController) OPTIONS(pattern string, handlers ...HandlerFunc)

OPTIONS is an alias to Add(pattern, "OPTIONS", handlers)

func (*BaseController) PATCH

func (c *BaseController) PATCH(pattern string, handlers ...HandlerFunc)

PATCH is an alias to Add(pattern, "PATCH", handlers)

func (*BaseController) POST

func (c *BaseController) POST(pattern string, handlers ...HandlerFunc)

POST is an alias to Add(pattern, "POST", handlers)

func (*BaseController) PUT

func (c *BaseController) PUT(pattern string, handlers ...HandlerFunc)

PUT is an alias to Add(pattern, "PUT", handlers)

func (*BaseController) Route

func (c *BaseController) Route(pattern string, method string, handler HandlerFunc)

Route define a route for the current controller. usage:

default methods is the same name as method
Route("/user", "GET", UserController.Get)
Route("/api/list", "GET", ApiController.List)
Route("/api/create", "POST", ApiController.Save)
Route("/api/update", "PUT", ApiController.Save)
Route("/api/delete", "DELETE", ApiController.Delete)

type BeforeFunc

type BeforeFunc func(ResponseWriter)

BeforeFunc defines a function called before the end of response.

type BodyPart

type BodyPart struct{ bytes.Buffer }

BodyPart is the structure used for html and plain.

func (*BodyPart) Set

func (w *BodyPart) Set(s string)

Set accepts a string as the contents of a BodyPart and replaces any existing data.

type ConfigData

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

ConfigData contains the configuration data

func DefaultConfig

func DefaultConfig() *ConfigData

DefaultConfig initialize the Config with basic configuration settings.

func (*ConfigData) Bool

func (c *ConfigData) Bool(key string) bool

Bool returns the config's value by specified key, cast to bool if possible. If data type don't match, return false

func (*ConfigData) Get

func (c *ConfigData) Get(key string) interface{}

Get return config's value by specified key.

func (*ConfigData) Int

func (c *ConfigData) Int(key string) int

Int returns the config's value by specified key, cast to int if possible. If data type don't match, return 0

func (*ConfigData) Set

func (c *ConfigData) Set(key string, value interface{})

Set updates a key with value.

func (*ConfigData) String

func (c *ConfigData) String(key string) string

String returns the config's value by specified key, cast to string if possible. If data type don't match, return an empty string

type Configuration

type Configuration interface {
	Set(key string, value interface{})
	Get(key string) interface{}
	String(key string) string
	Int(key string) int
	Bool(key string) bool
}

Configuration is the interface for app configuration.

var Config Configuration

Config is the framework global configuration

func LoadConfig

func LoadConfig(path string) Configuration

LoadConfig loads the configuration file from specified path and returns the Config object.

type Context

type Context struct {
	Request  *Request
	Response ResponseWriter
	Router   *Router
	Params   map[string]string

	Session Session
	I18n    *i18n.I18N
	Shared  map[string]interface{}

	Data map[string]interface{}
	// contains filtered or unexported fields
}

Context wraps Request and Response. It also provides methods for handling responses.

func NewContext

func NewContext(w ResponseWriter, r *Request) *Context

NewContext creates new context for the given w and r.

func (*Context) AddShared

func (c *Context) AddShared(key string, value interface{})

AddShared append value to context shared values

func (*Context) Error

func (c *Context) Error(code int, err error)

Error manage the error based on code

func (*Context) GetFlash

func (c *Context) GetFlash() (map[string]string, error)

GetFlash read the flash data from session.

func (*Context) GetShared

func (c *Context) GetShared(key string) interface{}

GetShared get value from context shared values

func (*Context) Header

func (c *Context) Header(key, value string)

Header sets or deletes the response headers.

func (*Context) JSON

func (c *Context) JSON(code int, obj interface{})

JSON renders as application/json with the given code.

func (*Context) Meta

func (c *Context) Meta(key, value string)

Meta sets or deletes the meta tags.

func (*Context) ParseForm

func (c *Context) ParseForm() error

ParseForm detects the post Content-Type and prepares the form fields. If the Content-Type is application/json the values are decoded into the request JSON and JSONRaw params.

func (*Context) ParseJSON

func (c *Context) ParseJSON(v interface{}) error

ParseJSON parse the body into your defined structure.

func (*Context) Plain

func (c *Context) Plain(code int, s string)

Plain sends a string.

func (*Context) Redirect

func (c *Context) Redirect(status int, url string)

Redirect the request to other url location.

func (*Context) Render

func (c *Context) Render(name string)

Render outputs using specified template.

func (*Context) Reset

func (c *Context) Reset()

Reset the context information.

func (*Context) WriteFlash

func (c *Context) WriteFlash(fd *FlashData) error

WriteFlash store the flash data into the current session.

type ContextPool

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

ContextPool contains the framework Context pool.

func NewContextPool

func NewContextPool() *ContextPool

NewContextPool create a new pool.

func (*ContextPool) Get

func (cp *ContextPool) Get(rw ResponseWriter, req *Request) (c *Context)

Get a context from the pool.

func (*ContextPool) Put

func (cp *ContextPool) Put(c *Context)

Put a context inside the pool.

type Controller

type Controller interface {
	Route(pattern string, method string, handler HandlerFunc)
	GET(pattern string, handlers ...HandlerFunc)
	POST(pattern string, handlers ...HandlerFunc)
	PUT(pattern string, handlers ...HandlerFunc)
	DELETE(pattern string, handlers ...HandlerFunc)
	PATCH(pattern string, handlers ...HandlerFunc)
	OPTIONS(pattern string, handlers ...HandlerFunc)
	HEAD(pattern string, handlers ...HandlerFunc)
	Any(pattern string, handlers ...HandlerFunc)
}

Controller interface for controller.

type Email

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

Email struct contains the email parameters.

func NewEmail

func NewEmail() *Email

NewEmail creates a new Email instance.

func (*Email) Attach

func (m *Email) Attach(filename, path string)

Attach adds an attachment to the email.

func (*Email) Bcc

func (m *Email) Bcc(emails ...string)

Bcc sets a list of blind carbon copy (BCC) addresses.

You can pass single or multiple addresses to this method.

mail.Bcc("first@email.com", "second@email.com")

func (*Email) ClearAttachments

func (m *Email) ClearAttachments()

ClearAttachments removes all attachments.

func (*Email) From

func (m *Email) From(addr string)

From sets the sender email address.

func (*Email) FromName

func (m *Email) FromName(name string)

FromName sets the sender name.

func (*Email) HTML

func (m *Email) HTML() *BodyPart

HTML returns a BodyPart for the HTML email body.

func (*Email) Plain

func (m *Email) Plain() *BodyPart

Plain returns a BodyPart for the plain-text email body.

func (*Email) ReplyTo

func (m *Email) ReplyTo(addr string)

ReplyTo sends the Reply-To email address.

func (*Email) Send

func (m *Email) Send() error

Send attempts to send the built email.

func (*Email) Subject

func (m *Email) Subject(subject string)

Subject sets the email subject.

func (*Email) To

func (m *Email) To(emails ...string)

To sets a list of recipient addresses.

You can pass single or multiple addresses to this method.

mail.To("first@email.com", "second@email.com")

type Emailer

type Emailer interface {
	From(email string)
	FromName(name string)
	ReplyTo(email string)
	To(emails ...string)
	Bcc(emails ...string)
	Subject(subject string)
	Send() error
	HTML() *BodyPart
	Plain() *BodyPart
}

Emailer is the interface for email sending.

type Engine

type Engine struct {
	Controllers []Controller

	Router Router
	View   Renderer

	GRPCServer *GRPCServer

	Path string
	// contains filtered or unexported fields
}

Engine is the framework struct.

var App *Engine

App contains a pointer to the framework instance. It's initialized automatically when application starts. To start HTTP listening use framework.Run()

func New

func New() *Engine

New initialize the engine and return an Engine struct.

func (*Engine) Init

func (engine *Engine) Init()

Init framework.

type FileSessionProvider

type FileSessionProvider struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

FileSessionProvider contains the cookie store.

func (*FileSessionProvider) Delete

func (fsp *FileSessionProvider) Delete(key string) error

Delete value in cookie session.

func (*FileSessionProvider) Destroy

func (fsp *FileSessionProvider) Destroy() error

Destroy entire session

func (*FileSessionProvider) GC

func (fsp *FileSessionProvider) GC()

GC clean expired sessions.

func (*FileSessionProvider) Get

func (fsp *FileSessionProvider) Get(key string) interface{}

Get value from cookie session.

func (*FileSessionProvider) Handler

func (fsp *FileSessionProvider) Handler(c *Context)

Handler

func (*FileSessionProvider) Init

Init checks if session id exists and return it.

func (*FileSessionProvider) Release

func (fsp *FileSessionProvider) Release(rw http.ResponseWriter, req *http.Request)

Release writes the cookie back to the http response cookie

func (*FileSessionProvider) SessionID

func (fsp *FileSessionProvider) SessionID() string

SessionID Return id of this cookie session

func (*FileSessionProvider) Set

func (fsp *FileSessionProvider) Set(key string, value interface{}) error

Set value to cookie session.

type FlashData

type FlashData struct {
	Data map[string]string
}

FlashData maintains data across requests.

func NewFlash

func NewFlash() *FlashData

NewFlash returns a new FlashData.

func (*FlashData) Set

func (fd *FlashData) Set(key string, msg string, args ...interface{})

Set message to flash.

type GRPCServer

type GRPCServer struct {
	*grpc.Server
}

GRPCServer is the structure that contains the gRPC server.

func NewGRPC

func NewGRPC(opt ...grpc.ServerOption) *GRPCServer

NewGRPC instantiates a new gRPC server.

type GRPCService

type GRPCService struct{}

GRPCService implements the gRPC Service. All user defined services must use this structure.

type GRPCServices

type GRPCServices interface{}

GRPCServices is the gRPC interface used for service registration.

type HandlerFunc

type HandlerFunc func(c *Context)

HandlerFunc defines the function type for controller requests.

type JSON

type JSON map[string]interface{}

JSON contains a generic map for output.

type JSONData

type JSONData struct {
	JSONValue
	// contains filtered or unexported fields
}

JSONData contains the array map to values.

func PrepareJSON

func PrepareJSON(data []byte) (*JSONData, error)

PrepareJSON instantiate the JSONData and unmarshal the data json, returns a JSONData struct.

func (*JSONData) Get

func (d *JSONData) Get(keys ...string) *JSONValue

Get a value using the specified keys, returns nil if value is not found.

func (*JSONData) PrepareInterface

func (d *JSONData) PrepareInterface(data interface{}) *JSONValue

PrepareInterface is a recursive function to translate json objects to maps.

func (*JSONData) Set

func (d *JSONData) Set(key string, value interface{})

Set a key with specified value.

type JSONValue

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

JSONValue contains values from JSONData.

func (*JSONValue) Array

func (v *JSONValue) Array() []interface{}

Array returns the values as an array.

func (*JSONValue) Bool

func (v *JSONValue) Bool() bool

Bool returns the value as string.

func (*JSONValue) Float64

func (v *JSONValue) Float64() float64

Float64 returns the value as float64.

func (*JSONValue) Int32

func (v *JSONValue) Int32() int32

Int32 converts and returns the value as int32.

func (*JSONValue) Int64

func (v *JSONValue) Int64() int64

Int64 converts and returns the value as int64.

func (*JSONValue) Map

func (v *JSONValue) Map() map[string]interface{}

Map returns the values as a map[string]interface{}.

func (*JSONValue) String

func (v *JSONValue) String() string

String returns the value as string.

type Level

type Level int

Level is the log gravity level

const (
	CRITICAL Level = iota
	ERROR
	WARNING
	INFO
	DEBUG
)

type Logger

type Logger struct {
	*log.Logger
}

Logger is the logger structure

var Log *Logger

Log is the framework global Logger

func NewLogger

func NewLogger(out io.Writer) *Logger

NewLogger create and return a new Logger instance

func (*Logger) Critical

func (l *Logger) Critical(str string)

Critical is an alias to log(CRITICAL, str)

func (*Logger) Criticalf

func (l *Logger) Criticalf(format string, a ...interface{})

Criticalf is an alias to log(CRITICAL, str)

func (*Logger) Debug

func (l *Logger) Debug(str string)

Debug is an alias to log(DEBUG, str)

func (*Logger) Debugf

func (l *Logger) Debugf(format string, a ...interface{})

Debugf is an alias to log(DEBUG, str)

func (*Logger) Error

func (l *Logger) Error(err error)

Error is an alias to log(ERROR, err)

func (*Logger) Errorf

func (l *Logger) Errorf(format string, a ...interface{})

Errorf is an alias to log(ERROR, err)

func (*Logger) Info

func (l *Logger) Info(str string)

Info is an alias to log(INFO, str)

func (*Logger) Infof

func (l *Logger) Infof(format string, a ...interface{})

Infof is an alias to log(INFO, str)

func (*Logger) Warning

func (l *Logger) Warning(str string)

Warning is an alias to log(WARNING, str)

func (*Logger) Warningf

func (l *Logger) Warningf(format string, a ...interface{})

Warningf is an alias to log(WARNING, str)

type Renderer

type Renderer interface {
	Render(out io.Writer, name string, data interface{}) error
	Parse(name string, data []byte) error
}

Renderer is the interface for template rendering.

func NewView

func NewView(viewDir string) (Renderer, error)

NewView returns a View with templates loaded from viewDir.

type Request

type Request struct {
	*http.Request

	JSON *JSONData
	// JsonRaw contains the raw json message.
	JSONRaw string
}

Request extends the default http.Request.

func (*Request) IP

func (r *Request) IP() string

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker

	// Before calls a function before the ResponseWriter has been written.
	Before(BeforeFunc)
	Status() int
}

ResponseWriter extends http.ResponseWriter.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type Route

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

Route contain the single route structure

type Router

type Router interface {
	Add(pattern string, method string, handlers ...HandlerFunc)
	ServeHTTP(rw http.ResponseWriter, req *http.Request)
}

Router is the framework router interface

func NewRouter

func NewRouter() Router

NewRouter instantiate a new Router

type Routes

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

Routes contains the framework routes, middleware and custom http error messages

func (*Routes) Add

func (r *Routes) Add(pattern string, method string, handlers ...HandlerFunc)

Add adds a new route to the app routes.

func (*Routes) OnError

func (r *Routes) OnError(code int, handlerFunc HandlerFunc)

OnError add a custom error handler

func (*Routes) ServeHTTP

func (r *Routes) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP handle the request based on defined routes.

func (*Routes) ServeStaticFiles

func (r *Routes) ServeStaticFiles(c *Context) bool

ServeStaticFiles check if requested path is a static file and serve the content.

type Rule

type Rule struct {
	Field        string
	Label        string
	Rule         string
	RuleParams   []string
	ErrorMessage string
}

Rule defines a single rule to check.

type Session

type Session interface {
	// Init checks if session id exists and return it.
	// if session does not exists, creates a new one.
	Init(http.ResponseWriter, *http.Request) (Session, error)
	// Release writes back the session header
	Release(http.ResponseWriter, *http.Request)
	// Set sets value to given key in session.
	Set(key string, value interface{}) error
	// Get gets value by given key in session.
	Get(string) interface{}
	// Delete deletes a key from session.
	Delete(string) error
	// Destroy the entire session
	Destroy() error
	// SessionID returns current session ID.
	SessionID() string
	// Handle
	Handler(c *Context)
}

Session contains the base session provider. Load configuration automatically from app.json file

func NewFileSessionProvider

func NewFileSessionProvider(config string) (Session, error)

NewFileSessionProvider returns a new file session provider.

func NewSession

func NewSession(name string, config string, provider SessionProvider) (Session, error)

NewSession creates the session provider instance using the provided name as provider and add it to the available session providers.

type SessionConfig

type SessionConfig struct {
	// Name is the cookie session name
	Name string `json:"name"`
	// //
	// Config string `json:"config"`
	// Domain limits cookie access to specified domain
	Domain string `json:"domain"`
	// MaxLifetime as seconds
	MaxLifetime int `json:"max_lifetime"`
	// Key is a private key used to encrypt session cookies
	Key string `json:"key"`
	// HTTPOnly allow access to cookies only via HTTP requests,
	// Set to true to protect against XSS exploits
	HTTPOnly bool `json:"http_only"`
}

SessionConfig contains the session instance default configuration.

type SessionProvider

type SessionProvider func(config string) (Session, error)

SessionProvider contains the session instance.

type Validator

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

Validator contains the methods for error checking. Values are retreived automatically from Context.

func NewValidator

func NewValidator(ctx *Context) *Validator

NewValidator returns a new Validator instance

func (*Validator) Alpha

func (v *Validator) Alpha(value string) bool

Alpha check if value contains only alpha (a-z) values

func (*Validator) AlphaNumeric

func (v *Validator) AlphaNumeric(value string) bool

AlphaNumeric check if value contains only alphanumeric values

func (*Validator) Base64

func (v *Validator) Base64(value string) bool

Base64 check if value is a valid Base64 string

func (*Validator) Bool

func (v *Validator) Bool(value interface{}) bool

Bool check if value is a bool

func (*Validator) Email

func (v *Validator) Email(value string) bool

Email check if value is a valid RFC5322 email address

func (*Validator) Exact

func (v *Validator) Exact(value int, compare int) bool

Exact check if value is equal to compare

func (*Validator) ExactLength

func (v *Validator) ExactLength(value string, length int) bool

ExactLength check if value length is equal to length

func (*Validator) Float

func (v *Validator) Float(value string) bool

Float check if value contains only digits

func (*Validator) Float64

func (v *Validator) Float64(value interface{}) bool

Float64 check if value is a float64

func (*Validator) IP

func (v *Validator) IP(value string) bool

IP check if value is a valid IP address

func (*Validator) Max

func (v *Validator) Max(value int, max int) bool

Max check if int value is lower or equal than max

func (*Validator) MaxLength

func (v *Validator) MaxLength(value string, max int) bool

MaxLength check if value length is lower or equal than max

func (*Validator) Min

func (v *Validator) Min(value int, min int) bool

Min check if int value is equal or greater than max

func (*Validator) MinLength

func (v *Validator) MinLength(value string, min int) bool

MinLength check if value is equal or greater than min

func (*Validator) Numeric

func (v *Validator) Numeric(value string) bool

Numeric check if value contains only digits

func (*Validator) Required

func (v *Validator) Required(value interface{}) bool

Required checks if value is not nil, empty, false or 0

func (*Validator) Rule

func (v *Validator) Rule(field string, label string, rule string, errorMessage string)

Rule adds a new rule to based on field. If the rule needs to pass parameters (f.e. MaxLength of 100) put the value into brackets: MaxLength[100]

func (*Validator) Rules

func (v *Validator) Rules(field string, label string, rules []string, errorMessages []string)

Rules adds multiple rules to the validator.

func (*Validator) String

func (v *Validator) String(value interface{}) bool

String check if value is a string

func (*Validator) URL

func (v *Validator) URL(value string) bool

URL check if value is a valid URL address

func (*Validator) Valid

func (v *Validator) Valid(values map[string]interface{}) error

Valid check if all rules are valid from provided map[string]string, otherwise return the rule error message.

func (*Validator) ValidForm

func (v *Validator) ValidForm() error

ValidForm check if all rules from current Request.Form are valid, otherwise return the rule error message.

func (*Validator) ValidJSON

func (v *Validator) ValidJSON() error

ValidJSON check if all rules from current Request.JSON are valid, otherwise return the rule error message.

type View

type View struct {
	template.Template
	// contains filtered or unexported fields
}

View implements the Renderer interface.

func (*View) EmbedShortcodes

func (s *View) EmbedShortcodes()

EmbedShortcodes defines the views shortcodes.

func (*View) EmbedTemplates

func (s *View) EmbedTemplates()

EmbedTemplates defines the views templates (e.g. google analytics).

func (*View) Parse

func (s *View) Parse(name string, data []byte) error

Parse the data template.

func (*View) Render

func (s *View) Render(out io.Writer, name string, data interface{}) error

Render executes the template by name.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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