just

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

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

Go to latest
Published: Jul 1, 2018 License: MIT Imports: 22 Imported by: 0

README

JUST Web Framework

Build Status CodeCov GoDoc

JUST — Web application framework, written in Go (GoLang). Inspired by the Gin (GoLang) and Symfony (PHP). JUST was not created to handle the huge volume of data and the more pre-empting analogues (Gin, Iris, Martini, ...). First I want to achieve comfort and reducing product development time ;-)

Ping / Pong example

package main

import "github.com/itrabbit/just"

func main() {
	a := just.New()
	a.GET("/ping", func(c *just.Context) just.IResponse {
		return c.S().Response(200, just.H{
			"message": "pong",
		})
	})
	a.Run(":80")
}

CLI

Install JUST CLI

go install github.com/itrabbit/just/cli/just-cli
Build i18n file from source
just-cli i18n:build -lang="en,ru" -dir="{full path to project dir}" -out="i18n.go"

Example result i18n:build (i18n.go)

// The file is generated using the CLI JUST.
// Change only translation strings!
// Everything else can be removed when re-generating!
// - - - - - 
// Last generated time: Sun, 07 Jan 2018 00:56:22 +05

package main

import "github.com/itrabbit/just"

func loadTranslations(t just.ITranslator) {
	if t != nil {
		t.AddTranslationMap("en", just.TranslationMap{
			"Hello World": "Hello World",
			"Payload": "Payload",
		})
		t.AddTranslationMap("ru", just.TranslationMap{
			"Hello World": "Hello World",
			"Payload": "Payload",
		})
	}
}

Usage i18n (main.go)

package main

import "github.com/itrabbit/just"

func main() {
	// Create app
	app := just.New()

	// Use i18n.go
	loadTranslations(app.Translator())
    
	app.GET("", func(c *just.Context) just.IResponse {
		return c.Serializer().
			Response(200, &just.H{
				"msg":     c.Tr("Hello World"),
				"payload": c.Tr("Payload"),
			})
	})
	app.Run(":8081")
}

Performance testing (on MacBook Pro 15 (2014))

goos: darwin
goarch: amd64
pkg: github.com/itrabbit/just

BenchmarkOneRoute:
10000000	       183 ns/op	      48 B/op	       1 allocs/op

BenchmarkRecoveryMiddleware:
10000000	       176 ns/op	      48 B/op	       1 allocs/op

BenchmarkLoggerMiddleware:
10000000	       173 ns/op	      48 B/op	       1 allocs/op

BenchmarkManyHandlers:
10000000	       174 ns/op	      48 B/op	       1 allocs/op

Benchmark5Params:
  500000	      3708 ns/op	     720 B/op	       8 allocs/op
  
BenchmarkOneRouteJSON:
 1000000	      1059 ns/op	     592 B/op	       6 allocs/op
 
BenchmarkOneRouteHTML:
  300000	      4501 ns/op	    1840 B/op	      28 allocs/op
  
BenchmarkOneRouteSet:
 3000000	       420 ns/op	     384 B/op	       3 allocs/op
 
BenchmarkOneRouteString:
10000000	       220 ns/op	      80 B/op	       2 allocs/op

BenchmarkManyRoutesFist:
10000000	       175 ns/op	      48 B/op	       1 allocs/op

BenchmarkManyRoutesLast:
10000000	       194 ns/op	      48 B/op	       1 allocs/op

Benchmark404:
10000000	       169 ns/op	      48 B/op	       1 allocs/op

Benchmark404Many:
 2000000	       607 ns/op	      48 B/op	       1 allocs/op

Serialize result finishing with filtration fields

package main

import (
	"time"
	
	"github.com/itrabbit/just"	
	"github.com/itrabbit/just/components/finalizer"
)

type PhoneNumber struct{
	E164 string `json:"e164"` 
}

type User struct {
	ID          uint64          `json:"id"`
	Phone       *PhoneNumber    `json:"phone,omitempty" group:"private" export:"E164"`
	CreatedAt   time.Time       `json:"created_at" group:"private"`
	UpdatedAt   time.Time       `json:"update_at" group:"private" exclude:"equal:CreatedAt"`
}

func main() {
	// Create new JUST application
	a := just.New()
	
	// replace def serializers
	finalizer.ReplaceSerializers(a)	
        
    a.GET("/{group:enum(public,private)}", func(c *just.Context) just.IResponse {
    	now := time.Now()
    	return c.Serializer().
    		    Response(200, finalizer.Input(
    		    	&User{
    		    		ID: 1,
    		    		Phone: &PhoneNumber{
    		    			E164: "+79000000000",
    		    		},
    		    		CreatedAt: now,
    		    		UpdatedAt: now,
    		    	}, 
    		    	c.ParamDef("group", "public"),
    		    ))
    })    
    a.Run(":80")
}

Result GET request http://localhost/public

{
    "id": 1
}

Result GET request http://localhost/private

{
    "id": 1,
    "phone": "+79000000000",
    "created_at": "2017-12-11T22:23:36.709146+05:00"    
}

More info

Routing examples

// Enums
http://localhost/api/{type:enum(object,item)}/{id:integer}

// True / False (0,1,t,f,true,false)
http://localhost/api/trigger/{value:boolean}

// Integer
http://localhost/api/object/{id:integer}

// Float
http://localhost/api/object/{id:float}

// Regexp
http://localhost/api/object/{id:regexp(\\d+)}

// String
http://localhost/api/object/{name}

// UUID
http://localhost/api/object/{uuid:uuid}

Donation to development

BTC: 1497z5VaY3AUEUYURS5b5fUTehVwv7wosX

DASH: XjBr7sqaCch4Lo1A7BctQz3HzRjybfpx2c

XRP: rEQwgdCr8Jma3GY2s55SLoZq2jmqmWUBDY

PayPal / Yandex Money: garin1221@yandex.ru

License

JUST is licensed under the MIT.

Documentation

Index

Constants

View Source
const (
	Version      = "v0.1.18"
	DebugEnvName = "JUST_DEBUG_MODE"
)
View Source
const (
	ContentTypeHeaderKey    = "Content-Type"
	StrongRedirectHeaderKey = "__StrongRedirect"
	ServeFileHeaderKey      = "__ServeFilePath"
)

Variables

View Source
var (
	ErrEmptyRequest          = errors.New("empty request")
	ErrEmptyRequestBody      = errors.New("empty request body")
	ErrNotFoundSerializer    = errors.New("not find serializer for content type in your request")
	ErrNotFoundUrlSerializer = errors.New("not find serializer for url query (application/x-www-form-urlencoded)")
)

Errors

View Source
var (
	ErrUnknownType         = errors.New("unknown type")
	ErrBlankTimeFormat     = errors.New("blank time format")
	ErrOnlyStructUrlEncode = errors.New("array and slice by root element not supported, only structure")
)
View Source
var (
	ErrInvalidContext         = errors.New("invalid context")
	ErrRecoverInvalidResponse = errors.New("invalid response, recover panic")
)

Errors

View Source
var (
	ErrEmptyReader       = errors.New("reader is empty")
	ErrUnsupportedReader = errors.New("reader is not supported")
)

Errors

View Source
var (
	ErrEmptyTemplates = errors.New("have hot templates")
)

Errors

View Source
var (
	ErrSerializeOperationsDisabled = errors.New("serialize operations disabled")
)

Functions

func IsDebug

func IsDebug() bool

func SetDebugMode

func SetDebugMode(value bool)

Change debug mode

func Validation

func Validation(obj interface{}) []error

Validation of the structure of the object according to the parameters within the tags.

Types

type Context

type Context struct {

	// Public props.
	Meta                map[string]interface{} // Metadata.
	Request             *http.Request          // HTTP request.
	IsFrozenRequestBody bool                   // Use frozen request body (default true).
	// contains filtered or unexported fields
}

Request Context struct.

func (*Context) Bind

func (c *Context) Bind(ptr interface{}) error

DeSerializing body or query to object

func (*Context) ClientIP

func (c *Context) ClientIP(forwarded bool) string

ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.

func (*Context) ContentType

func (c *Context) ContentType() string

Get the Content-Type header of the request.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.

func (*Context) CookieDef

func (c *Context) CookieDef(name string, def string) string

func (*Context) DetectedSerializerName

func (c *Context) DetectedSerializerName() string

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

Get multipart.FileHeader from MultipartForm by name.

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, ok bool)

Get metadata by key.

func (*Context) GetBool

func (c *Context) GetBool(key string) (value bool, ok bool)

Get bool metadata by key.

func (*Context) GetBoolDef

func (c *Context) GetBoolDef(key string, def bool) bool

Get bool metadata by key with default value.

func (*Context) GetDef

func (c *Context) GetDef(key string, def interface{}) interface{}

Get metadata by key with default value.

func (*Context) GetDuration

func (c *Context) GetDuration(key string) (value time.Duration, ok bool)

Get duration metadata by key.

func (*Context) GetDurationDef

func (c *Context) GetDurationDef(key string, def time.Duration) time.Duration

Get duration metadata by key with default value.

func (*Context) GetFloat

func (c *Context) GetFloat(key string) (value float64, ok bool)

Get integer metadata by key.

func (*Context) GetFloatDef

func (c *Context) GetFloatDef(key string, def float64) float64

Get float metadata by key with default value.

func (*Context) GetInt

func (c *Context) GetInt(key string) (value int64, ok bool)

Get integer metadata by key.

func (*Context) GetIntDef

func (c *Context) GetIntDef(key string, def int64) int64

Get integer metadata by key with default value.

func (*Context) GetStr

func (c *Context) GetStr(key string) (value string, ok bool)

Get string metadata by key.

func (*Context) GetStrDef

func (c *Context) GetStrDef(key string, def string) string

Get string metadata by key with default value.

func (*Context) GetUint

func (c *Context) GetUint(key string) (value uint64, ok bool)

Get unsigned integer metadata by key.

func (*Context) GetUintDef

func (c *Context) GetUintDef(key string, def uint64) uint64

Get unsigned integer metadata by key with default value.

func (*Context) IsLocalRequest

func (c *Context) IsLocalRequest() bool

func (*Context) IsValid

func (c *Context) IsValid() bool

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm is the parsed multipart form, including file uploads.

func (*Context) MustCookie

func (c *Context) MustCookie(name string) string

func (*Context) MustGet

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

func (*Context) MustParam

func (c *Context) MustParam(name string) string

func (*Context) MustParamBool

func (c *Context) MustParamBool(name string) bool

func (*Context) MustParamFloat

func (c *Context) MustParamFloat(name string) float64

func (*Context) MustParamInt

func (c *Context) MustParamInt(name string) int64

func (*Context) MustPostForm

func (c *Context) MustPostForm(key string) string

func (*Context) MustPostFormArray

func (c *Context) MustPostFormArray(key string) []string

func (*Context) MustPostFormBool

func (c *Context) MustPostFormBool(key string) bool

func (*Context) MustPostFormFloat

func (c *Context) MustPostFormFloat(key string) float64

func (*Context) MustPostFormInt

func (c *Context) MustPostFormInt(key string) int64

func (*Context) MustQuery

func (c *Context) MustQuery(key string) string

func (*Context) MustQueryArray

func (c *Context) MustQueryArray(key string) []string

func (*Context) MustQueryBool

func (c *Context) MustQueryBool(key string) bool

func (*Context) MustQueryFloat

func (c *Context) MustQueryFloat(key string) float64

func (*Context) MustQueryInt

func (c *Context) MustQueryInt(key string) int64

func (*Context) MustRequestHeader

func (c *Context) MustRequestHeader(key string) string

func (*Context) Next

func (c *Context) Next() IResponse

Turn to elective next handler

func (*Context) Param

func (c *Context) Param(name string) (value string, ok bool)

Get route param by name.

func (*Context) ParamBool

func (c *Context) ParamBool(name string) (value bool, ok bool)

Get bool route param by name.

func (*Context) ParamBoolDef

func (c *Context) ParamBoolDef(name string, def bool) bool

Get bool route param by name with the default value.

func (*Context) ParamDef

func (c *Context) ParamDef(name string, def string) string

Get route param by name with the default value.

func (*Context) ParamFloat

func (c *Context) ParamFloat(name string) (value float64, ok bool)

Get float route param by name.

func (*Context) ParamFloatDef

func (c *Context) ParamFloatDef(name string, def float64) float64

Get float route param by name with the default value.

func (*Context) ParamInt

func (c *Context) ParamInt(name string) (value int64, ok bool)

Get integer route param by name.

func (*Context) ParamIntDef

func (c *Context) ParamIntDef(name string, def int64) int64

Get integer route param by name with the default value.

func (*Context) PostForm

func (c *Context) PostForm(key string) (string, bool)

PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string `("")`.

func (*Context) PostFormArray

func (c *Context) PostFormArray(key string) ([]string, bool)

func (*Context) PostFormArrayDef

func (c *Context) PostFormArrayDef(key string, def []string) []string

func (*Context) PostFormBool

func (c *Context) PostFormBool(key string) (bool, bool)

func (*Context) PostFormBoolDef

func (c *Context) PostFormBoolDef(key string, def bool) bool

func (*Context) PostFormDef

func (c *Context) PostFormDef(key, def string) string

PostForm returns the specified key from a POST urlencoded form or multipart form with default value.

func (*Context) PostFormFloat

func (c *Context) PostFormFloat(key string) (float64, bool)

func (*Context) PostFormFloatDef

func (c *Context) PostFormFloatDef(key string, def float64) float64

func (*Context) PostFormInt

func (c *Context) PostFormInt(key string) (int64, bool)

func (*Context) PostFormIntDef

func (c *Context) PostFormIntDef(key string, def int64) int64

func (*Context) Query

func (c *Context) Query(key string) (string, bool)

Get query param by key.

func (*Context) QueryArray

func (c *Context) QueryArray(key string) ([]string, bool)

Get array query param by key.

func (*Context) QueryArrayDef

func (c *Context) QueryArrayDef(key string, def []string) []string

Get array query param by key with default value.

func (*Context) QueryBool

func (c *Context) QueryBool(key string) (bool, bool)

Get bool query param by key.

func (*Context) QueryBoolDef

func (c *Context) QueryBoolDef(key string, def bool) bool

Get bool query param by key with default value.

func (*Context) QueryDef

func (c *Context) QueryDef(key, def string) string

Get query param by key with default value.

func (*Context) QueryFloat

func (c *Context) QueryFloat(key string) (float64, bool)

Get float query param by key.

func (*Context) QueryFloatDef

func (c *Context) QueryFloatDef(key string, def float64) float64

Get float query param by key with default value.

func (*Context) QueryInt

func (c *Context) QueryInt(key string) (int64, bool)

Get integer query param by key.

func (*Context) QueryIntDef

func (c *Context) QueryIntDef(key string, def int64) int64

Get integer query param by key with default value.

func (*Context) R

func (c *Context) R(name string) IRenderer

Short name for current renderer.

func (*Context) Renderer

func (c *Context) Renderer(name string) IRenderer

Current template renderer.

func (*Context) RequestHeader

func (c *Context) RequestHeader(key string) (string, bool)

Get request header string value by key.

func (*Context) RequestHeaderDef

func (c *Context) RequestHeaderDef(key string, def string) string

Get request header string value by key with default value.

func (*Context) RequestUrlScheme

func (c *Context) RequestUrlScheme() string

Get url scheme from request, supported X-Scheme and X-Forwarded-Proto headers.

func (*Context) ResetBodyReaderPosition

func (c *Context) ResetBodyReaderPosition() error

Reset body reader position.

func (*Context) RouteBasePath

func (c *Context) RouteBasePath() string

Current route path.

func (*Context) S

func (c *Context) S(names ...string) ISerializer

Short name for serializer method

func (*Context) Serializer

func (c *Context) Serializer(names ...string) ISerializer

Get serializer by name or content type (without names - default serializer, or auto detected serializer).

func (*Context) Set

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

Set metadata by key.

func (*Context) Tr

func (c *Context) Tr(message string, vars ...interface{}) string

Short name for translate text method.

func (*Context) Trans

func (c *Context) Trans(message string, vars ...interface{}) string

Translate text by current language.

func (*Context) UserAgent

func (c *Context) UserAgent() string

Get user agent from request headers.

type Error

type Error struct {
	XMLName  xml.Name     `json:"-" xml:"error"`
	Code     string       `json:"code,omitempty" xml:"code,attr,omitempty"`
	Message  string       `json:"msg" xml:"msg"`
	Causes   []ErrorCause `json:"causes,omitempty" xml:"causes,omitempty"`
	Metadata H            `json:"metadata,omitempty" xml:"metadata,omitempty"`
}

Error struct.

func NewError

func NewError(code, msg string) *Error

Method of quickly creating errors.

func (*Error) AddCause

func (e *Error) AddCause(target, path, desc string) *Error

Adds cause of errors.

func (*Error) Error

func (e *Error) Error() string

Text error.

func (*Error) SetMetadata

func (e *Error) SetMetadata(meta H) *Error

Set metadata to error.

type ErrorCause

type ErrorCause struct {
	XMLName     xml.Name `json:"-" xml:"cause"`
	Path        string   `json:"path,omitempty" xml:"path,attr,omitempty"`
	Target      string   `json:"target,omitempty" xml:"target,attr,omitempty"`
	Description string   `json:"desc,omitempty" xml:"desc,omitempty"`
}

Reason struct for error.

type FormSerializer

type FormSerializer struct {
	Ch              string
	OnlyDeserialize bool
}

Form serializer (form-data, x-www-form-urlencoded).

func (FormSerializer) Charset

func (s FormSerializer) Charset() string

func (FormSerializer) DefaultContentType

func (s FormSerializer) DefaultContentType(withCharset bool) string

func (FormSerializer) Deserialize

func (FormSerializer) Deserialize(data []byte, v interface{}) error

func (FormSerializer) Name

func (FormSerializer) Name() string

func (FormSerializer) Response

func (s FormSerializer) Response(status int, data interface{}) IResponse

func (FormSerializer) Serialize

func (s FormSerializer) Serialize(v interface{}) ([]byte, error)

type H

type H map[string]interface{}

H is a shortcup for map[string]interface{} (to improve code reading).

func (H) MarshalXML

func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error

Overriding for Marshal to XML

type HTMLRenderer

type HTMLRenderer struct {
	Charset string
	// contains filtered or unexported fields
}

HTML template engine.

func (*HTMLRenderer) AddFunc

func (r *HTMLRenderer) AddFunc(name string, i interface{}) IRenderer

Add Func to HTML templates.

func (*HTMLRenderer) DefaultContentType

func (r *HTMLRenderer) DefaultContentType(withCharset bool) string

Content Type by default for HTMLRenderer.

func (*HTMLRenderer) LoadTemplateFiles

func (r *HTMLRenderer) LoadTemplateFiles(fileNames ...string) error

Load HTML template files.

func (*HTMLRenderer) LoadTemplateGlob

func (r *HTMLRenderer) LoadTemplateGlob(name, pattern string) error

Load HTML template glob.

func (*HTMLRenderer) RemoveFunc

func (r *HTMLRenderer) RemoveFunc(name string) IRenderer

Remove Func from HTML templates.

func (*HTMLRenderer) Render

func (r *HTMLRenderer) Render(name string, data interface{}) ([]byte, error)

Render HTML to bytes.

func (*HTMLRenderer) Response

func (r *HTMLRenderer) Response(status int, name string, data interface{}) IResponse

Response from HTML template.

type HandlerFunc

type HandlerFunc func(*Context) IResponse

Method of processing a request or middleware.

type IApplication

type IApplication interface {
	IRouter

	Profiler() IProfiler
	Translator() ITranslator
	SerializerManager() ISerializerManager
	TemplatingManager() ITemplatingManager

	LocalDo(req *http.Request) IResponse

	SetProfiler(p IProfiler) IApplication
	SetTranslator(t ITranslator) IApplication
	SetNoRouteHandler(handler HandlerFunc) IApplication
	SetNoImplementedHandler(handler HandlerFunc) IApplication

	ServeHTTP(w http.ResponseWriter, req *http.Request)

	Run(address string) error
	RunTLS(address, certFile, keyFile string) error
}

JUST Application interface.

func New

func New() IApplication

Create new default JUST application.

func NewClear

func NewClear() IApplication

Create new clear JUST application. Without serializers and renderers.

func SetDefRenderers

func SetDefRenderers(app IApplication) IApplication

Set default renderers (HTML UTF-8)

func SetDefSerializers

func SetDefSerializers(app IApplication) IApplication

Set default serializer to just application (json, xml, form-data, x-www-form-urlencoded)

type IProfiler

type IProfiler interface {
	OnStartRequest(*http.Request)            // Event start processing HTTP request.
	OnSelectRoute(*http.Request, IRouteInfo) // Event select route for request.
	OnWriteResponseData([]byte)              // Event write data to response.
	OnWriteResponseHeader(int, http.Header)  // Event write headers to response.
	Info(...interface{})                     // Send info message to profiler.
	Error(...interface{})                    // Send error message to profiler.
	Warning(...interface{})                  // Send warning message to profiler.
	Debug(...interface{})                    // Send debug message to profiler.
}

Profiler interface.

type IRenderer

type IRenderer interface {
	DefaultContentType(withCharset bool) string
	LoadTemplateFiles(fileNames ...string) error
	LoadTemplateGlob(name, pattern string) error
	AddFunc(name string, i interface{}) IRenderer
	RemoveFunc(name string) IRenderer
	Render(name string, data interface{}) ([]byte, error)
	Response(status int, name string, data interface{}) IResponse
}

Interface for rendering templates.

type IResponse

type IResponse interface {
	// Checkers
	HasData() bool
	HasHeaders() bool
	HasStreamHandler() bool
	// Getters
	GetData() []byte
	GetStatus() int
	GetHeaders() map[string]string
	GetStreamHandler() (http.HandlerFunc, bool)
}

Response interface.

func FileResponse

func FileResponse(filePath string) IResponse

Create a response in the form of a local file.

func JsonResponse

func JsonResponse(status int, v interface{}) IResponse

Create a JSON response.

func RedirectResponse

func RedirectResponse(status int, location string) IResponse

Create a redirect response (Use _StrongRedirect in header to set location)

func StreamResponse

func StreamResponse(handler http.HandlerFunc) IResponse

Create a stream response.

func XmlResponse

func XmlResponse(status int, v interface{}) IResponse

Create a XML response.

type IRoute

type IRoute interface {
	IRouteInfo

	// Use middleware.
	Use(...HandlerFunc) IRoute

	// Processing of requests to the application server.
	Handle(string, string, ...HandlerFunc) IRoute
	ANY(string, ...HandlerFunc) IRoute
	GET(string, ...HandlerFunc) IRoute
	POST(string, ...HandlerFunc) IRoute
	DELETE(string, ...HandlerFunc) IRoute
	PATCH(string, ...HandlerFunc) IRoute
	PUT(string, ...HandlerFunc) IRoute
	OPTIONS(string, ...HandlerFunc) IRoute
	HEAD(string, ...HandlerFunc) IRoute

	StaticFile(string, string) IRoute

	Static(string, string) IRoute
	StaticFS(string, http.FileSystem) IRoute

	CheckPath(string) (map[string]string, bool)
}

Route interface.

type IRouteInfo

type IRouteInfo interface {
	BasePath() string
	CountHandlers() int
	HandlerByIndex(index int) (HandlerFunc, bool)
}

Interface information on route.

type IRouter

type IRouter interface {
	IRoute
	Group(string, ...HandlerFunc) IRouter
}

Router interface.

type ISerializeInput

type ISerializeInput interface {
	Data() interface{}
	Options() interface{}
}

Input interface serializer.

type ISerializer

type ISerializer interface {
	Name() string                                    // Name serializer.
	Charset() string                                 // Get Charset serializer.
	DefaultContentType(withCharset bool) string      // The default content type.
	Serialize(interface{}) ([]byte, error)           // Serialize obj/objs to bytes.
	Deserialize([]byte, interface{}) error           // Deserialize bytes tp obj/objs.
	Response(status int, data interface{}) IResponse // Serialize obj/objs to IResponse.
}

Serializer interface.

type ISerializerManager

type ISerializerManager interface {
	Names() []string
	DefaultName() (string, bool)
	SetDefaultName(string) ISerializerManager
	SetSerializer(string, []string, ISerializer) ISerializerManager
	Serializer(n string, byContent bool) ISerializer
}

Serializer manager interface to manage the serializers.

type ITemplatingManager

type ITemplatingManager interface {
	SetRenderer(name string, r IRenderer)
	Renderer(name string) IRenderer
}

Interface Template Manager.

type ITranslator

type ITranslator interface {
	DefaultLocale() string
	SetDefaultLocale(locale string) ITranslator
	AddTranslationMap(locale string, m TranslationMap) ITranslator
	Trans(locale string, message string, vars ...interface{}) string // Translate text for locale and vars.
}

Translator interface.

type JsonSerializer

type JsonSerializer struct {
	Ch string // Charset for generate Content-Type header.
}

Base JSON serializer.

func (JsonSerializer) Charset

func (s JsonSerializer) Charset() string

func (JsonSerializer) DefaultContentType

func (s JsonSerializer) DefaultContentType(withCharset bool) string

func (JsonSerializer) Deserialize

func (JsonSerializer) Deserialize(data []byte, v interface{}) error

func (JsonSerializer) Name

func (JsonSerializer) Name() string

func (JsonSerializer) Response

func (s JsonSerializer) Response(status int, data interface{}) IResponse

func (JsonSerializer) Serialize

func (JsonSerializer) Serialize(v interface{}) ([]byte, error)

type Response

type Response struct {
	Status  int               // HTTP status (200, 201,...).
	Bytes   []byte            // Data bytes.
	Headers map[string]string // Response headers.
	Stream  http.HandlerFunc  // Stream method, to support standard HTTP package, as well as to work with WS.
}

Base Response struct.

func (Response) GetData

func (r Response) GetData() []byte

func (*Response) GetHeaders

func (r *Response) GetHeaders() map[string]string

func (Response) GetStatus

func (r Response) GetStatus() int

func (Response) GetStreamHandler

func (r Response) GetStreamHandler() (http.HandlerFunc, bool)

func (Response) HasData

func (r Response) HasData() bool

func (Response) HasHeaders

func (r Response) HasHeaders() bool

func (Response) HasStreamHandler

func (r Response) HasStreamHandler() bool

type Router

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

Base Router struct.

func (*Router) ANY

func (r *Router) ANY(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) BasePath

func (r *Router) BasePath() string

func (*Router) CheckPath

func (r *Router) CheckPath(path string) (map[string]string, bool)

func (*Router) CountHandlers

func (r *Router) CountHandlers() int

func (*Router) DELETE

func (r *Router) DELETE(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) GET

func (r *Router) GET(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) Group

func (r *Router) Group(relativePath string, handlers ...HandlerFunc) IRouter

Create group router. The group does not support regular expressions, text only.

func (*Router) HEAD

func (r *Router) HEAD(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) Handle

func (r *Router) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoute

Create a HTTP request handler.

func (*Router) HandlerByIndex

func (r *Router) HandlerByIndex(index int) (HandlerFunc, bool)

func (*Router) OPTIONS

func (r *Router) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) PATCH

func (r *Router) PATCH(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) POST

func (r *Router) POST(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) PUT

func (r *Router) PUT(relativePath string, handlers ...HandlerFunc) IRoute

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

func (*Router) Static

func (r *Router) Static(relativePath, root string) IRoute

Static serves files from the given file system root. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use: `router.Static("/static", "/var/www")`

func (*Router) StaticFS

func (r *Router) StaticFS(relativePath string, fs http.FileSystem) IRoute

StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.

func (*Router) StaticFile

func (r *Router) StaticFile(relativePath, filePath string) IRoute

StaticFile registers a single route in order to server a single file of the local filesystem. `router.StaticFile("favicon.ico", "./resources/favicon.ico")`

func (*Router) Use

func (r *Router) Use(middleware ...HandlerFunc) IRoute

Use middleware.

type TranslationMap

type TranslationMap map[string]string

Translation map for one language.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

Structure validation errors.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Validation error text.

type XmlSerializer

type XmlSerializer struct {
	Ch string // Charset for generate Content-Type header.
}

Base XML serializer.

func (XmlSerializer) Charset

func (s XmlSerializer) Charset() string

func (XmlSerializer) DefaultContentType

func (s XmlSerializer) DefaultContentType(withCharset bool) string

func (XmlSerializer) Deserialize

func (XmlSerializer) Deserialize(data []byte, v interface{}) error

func (XmlSerializer) Name

func (XmlSerializer) Name() string

func (XmlSerializer) Response

func (s XmlSerializer) Response(status int, data interface{}) IResponse

func (XmlSerializer) Serialize

func (XmlSerializer) Serialize(v interface{}) ([]byte, error)

Directories

Path Synopsis
cli
components
examples

Jump to

Keyboard shortcuts

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