evo

package module
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2021 License: MIT Imports: 59 Imported by: 8

README

EVO Web Application Development Framework

Go Report Card Discord Discord Chat

EVO is a powerful package for quickly writing modular web applications/services in Golang aimed both backend and frontend.

Features

  • Think once, Code less, Do more!
  • Aim both frontend and backend
  • Extremely simple to use.
  • Awesome superfast path matching and routing.
  • Modular & Extensible
  • A lot of tweaks and improvments
  • A lot of useful functions
  • A lot of UI components and integrations
  • A lot of usable/reusable apps to include and use
  • Live reload
  • High performance
  • Superfast template engine
  • Actively maintained
  • Docker Integration

Builtin Apps

  • Admin simple extensible user panel
  • Auth fully featured user/group/role/permission management set of apies
  • AdminLTE adminlte template ready to use!
  • Query dynamic multi purpose data query api
  • Settings create settings view for all of your apps

Documentation

Documentation (WIKI)

Quick Start
  • Installation
  • Create new project
  • Examples

Todo

  • i18n
  • User Management app
  • Journal App
  • Log App
  • Swagger
  • Documentation (WIKI)
  • Sample Apps
  • Clear Libraries
  • Improve Manager
  • Keycloak login
  • Social Login
  • Websocket integration
  • CodeTest integration
  • Implementation test case of code

Shoulders of Giants

EVO stands on shoulder of great projects or inspired by them.

Fiber

An Express-inspired web framework written in Go


GORM

The fantastic ORM library for Golang


Jet Template Engine for Go

Jet is a template engine developed to be easy to use, powerful, dynamic, yet secure and very fast.


mapstructure

mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling.


Contact

  • Join the community and chat with us in real-time on Discord.
  • Submit requests and issues on GitHub.

Contributors

Reza Allan Nava
Reza Allan

Documentation

Index

Constants

View Source
const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8

)

HTTP methods were copied from net/http.

View Source
const (
	MIMETextXML               = "text/xml"
	MIMETextHTML              = "text/html"
	MIMETextPlain             = "text/plain"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationJSON       = "application/json"
	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"
	MIMEOctetStream           = "application/octet-stream"
	MIMEMultipartForm         = "multipart/form-data"

	MIMETextXMLCharsetUTF8               = "text/xml; charset=utf-8"
	MIMETextHTMLCharsetUTF8              = "text/html; charset=utf-8"
	MIMETextPlainCharsetUTF8             = "text/plain; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8        = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8       = "application/json; charset=utf-8"
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	StatusContinue                      = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols            = 101 // RFC 7231, 6.2.2
	StatusProcessing                    = 102 // RFC 2518, 10.1
	StatusEarlyHints                    = 103 // RFC 8297
	StatusOK                            = 200 // RFC 7231, 6.3.1
	StatusCreated                       = 201 // RFC 7231, 6.3.2
	StatusAccepted                      = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInformation   = 203 // RFC 7231, 6.3.4
	StatusNoContent                     = 204 // RFC 7231, 6.3.5
	StatusResetContent                  = 205 // RFC 7231, 6.3.6
	StatusPartialContent                = 206 // RFC 7233, 4.1
	StatusMultiStatus                   = 207 // RFC 4918, 11.1
	StatusAlreadyReported               = 208 // RFC 5842, 7.1
	StatusIMUsed                        = 226 // RFC 3229, 10.4.1
	StatusMultipleChoices               = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently              = 301 // RFC 7231, 6.4.2
	StatusFound                         = 302 // RFC 7231, 6.4.3
	StatusSeeOther                      = 303 // RFC 7231, 6.4.4
	StatusNotModified                   = 304 // RFC 7232, 4.1
	StatusUseProxy                      = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect             = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect             = 308 // RFC 7538, 3
	StatusBadRequest                    = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                  = 401 // RFC 7235, 3.1
	StatusPaymentRequired               = 402 // RFC 7231, 6.5.2
	StatusForbidden                     = 403 // RFC 7231, 6.5.3
	StatusNotFound                      = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed              = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                 = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired             = 407 // RFC 7235, 3.2
	StatusRequestTimeout                = 408 // RFC 7231, 6.5.7
	StatusConflict                      = 409 // RFC 7231, 6.5.8
	StatusGone                          = 410 // RFC 7231, 6.5.9
	StatusLengthRequired                = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed            = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge         = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong             = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType          = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable  = 416 // RFC 7233, 4.4
	StatusExpectationFailed             = 417 // RFC 7231, 6.5.14
	StatusTeapot                        = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest            = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity           = 422 // RFC 4918, 11.2
	StatusLocked                        = 423 // RFC 4918, 11.3
	StatusFailedDependency              = 424 // RFC 4918, 11.4
	StatusTooEarly                      = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired               = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired          = 428 // RFC 6585, 3
	StatusTooManyRequests               = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge   = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons    = 451 // RFC 7725, 3
	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were copied from net/http.

View Source
const (
	HeaderAuthorization                   = "Authorization"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderAge                             = "Age"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderExpires                         = "Expires"
	HeaderPragma                          = "Pragma"
	HeaderWarning                         = "Warning"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderContentDPR                      = "Content-DPR"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderSaveData                        = "Save-Data"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWidth                           = "Width"
	HeaderETag                            = "ETag"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderVary                            = "Vary"
	HeaderConnection                      = "Connection"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderCookie                          = "Cookie"
	HeaderExpect                          = "Expect"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderOrigin                          = "Origin"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             = "DNT"
	HeaderTk                              = "Tk"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentType                     = "Content-Type"
	HeaderForwarded                       = "Forwarded"
	HeaderVia                             = "Via"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderLocation                        = "Location"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderUserAgent                       = "User-Agent"
	HeaderAllow                           = "Allow"
	HeaderServer                          = "Server"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderContentRange                    = "Content-Range"
	HeaderIfRange                         = "If-Range"
	HeaderRange                           = "Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderLastEventID                     = "Last-Event-ID"
	HeaderNEL                             = "NEL"
	HeaderPingFrom                        = "Ping-From"
	HeaderPingTo                          = "Ping-To"
	HeaderReportTo                        = "Report-To"
	HeaderTE                              = "TE"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderSecWebSocketAccept              = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions          = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey                 = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol            = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion             = "Sec-WebSocket-Version"
	HeaderAcceptPatch                     = "Accept-Patch"
	HeaderAcceptPushPolicy                = "Accept-Push-Policy"
	HeaderAcceptSignature                 = "Accept-Signature"
	HeaderAltSvc                          = "Alt-Svc"
	HeaderDate                            = "Date"
	HeaderIndex                           = "Index"
	HeaderLargeAllocation                 = "Large-Allocation"
	HeaderLink                            = "Link"
	HeaderPushPolicy                      = "Push-Policy"
	HeaderRetryAfter                      = "Retry-After"
	HeaderServerTiming                    = "Server-Timing"
	HeaderSignature                       = "Signature"
	HeaderSignedHeaders                   = "Signed-Headers"
	HeaderSourceMap                       = "SourceMap"
	HeaderUpgrade                         = "Upgrade"
	HeaderXDNSPrefetchControl             = "X-DNS-Prefetch-Control"
	HeaderXPingback                       = "X-Pingback"
	HeaderXRequestID                      = "X-Request-ID"
	HeaderXRequestedWith                  = "X-Requested-With"
	HeaderXRobotsTag                      = "X-Robots-Tag"
	HeaderXUACompatible                   = "X-UA-Compatible"
)

HTTP Headers were copied from net/http.

Variables

View Source
var (
	ErrBadRequest                    = NewError(StatusBadRequest)                    // RFC 7231, 6.5.1
	ErrUnauthorized                  = NewError(StatusUnauthorized)                  // RFC 7235, 3.1
	ErrPaymentRequired               = NewError(StatusPaymentRequired)               // RFC 7231, 6.5.2
	ErrForbidden                     = NewError(StatusForbidden)                     // RFC 7231, 6.5.3
	ErrNotFound                      = NewError(StatusNotFound)                      // RFC 7231, 6.5.4
	ErrMethodNotAllowed              = NewError(StatusMethodNotAllowed)              // RFC 7231, 6.5.5
	ErrNotAcceptable                 = NewError(StatusNotAcceptable)                 // RFC 7231, 6.5.6
	ErrProxyAuthRequired             = NewError(StatusProxyAuthRequired)             // RFC 7235, 3.2
	ErrRequestTimeout                = NewError(StatusRequestTimeout)                // RFC 7231, 6.5.7
	ErrConflict                      = NewError(StatusConflict)                      // RFC 7231, 6.5.8
	ErrGone                          = NewError(StatusGone)                          // RFC 7231, 6.5.9
	ErrLengthRequired                = NewError(StatusLengthRequired)                // RFC 7231, 6.5.10
	ErrPreconditionFailed            = NewError(StatusPreconditionFailed)            // RFC 7232, 4.2
	ErrRequestEntityTooLarge         = NewError(StatusRequestEntityTooLarge)         // RFC 7231, 6.5.11
	ErrRequestURITooLong             = NewError(StatusRequestURITooLong)             // RFC 7231, 6.5.12
	ErrUnsupportedMediaType          = NewError(StatusUnsupportedMediaType)          // RFC 7231, 6.5.13
	ErrRequestedRangeNotSatisfiable  = NewError(StatusRequestedRangeNotSatisfiable)  // RFC 7233, 4.4
	ErrExpectationFailed             = NewError(StatusExpectationFailed)             // RFC 7231, 6.5.14
	ErrTeapot                        = NewError(StatusTeapot)                        // RFC 7168, 2.3.3
	ErrMisdirectedRequest            = NewError(StatusMisdirectedRequest)            // RFC 7540, 9.1.2
	ErrUnprocessableEntity           = NewError(StatusUnprocessableEntity)           // RFC 4918, 11.2
	ErrLocked                        = NewError(StatusLocked)                        // RFC 4918, 11.3
	ErrFailedDependency              = NewError(StatusFailedDependency)              // RFC 4918, 11.4
	ErrTooEarly                      = NewError(StatusTooEarly)                      // RFC 8470, 5.2.
	ErrUpgradeRequired               = NewError(StatusUpgradeRequired)               // RFC 7231, 6.5.15
	ErrPreconditionRequired          = NewError(StatusPreconditionRequired)          // RFC 6585, 3
	ErrTooManyRequests               = NewError(StatusTooManyRequests)               // RFC 6585, 4
	ErrRequestHeaderFieldsTooLarge   = NewError(StatusRequestHeaderFieldsTooLarge)   // RFC 6585, 5
	ErrUnavailableForLegalReasons    = NewError(StatusUnavailableForLegalReasons)    // RFC 7725, 3
	ErrInternalServerError           = NewError(StatusInternalServerError)           // RFC 7231, 6.6.1
	ErrNotImplemented                = NewError(StatusNotImplemented)                // RFC 7231, 6.6.2
	ErrBadGateway                    = NewError(StatusBadGateway)                    // RFC 7231, 6.6.3
	ErrServiceUnavailable            = NewError(StatusServiceUnavailable)            // RFC 7231, 6.6.4
	ErrGatewayTimeout                = NewError(StatusGatewayTimeout)                // RFC 7231, 6.6.5
	ErrHTTPVersionNotSupported       = NewError(StatusHTTPVersionNotSupported)       // RFC 7231, 6.6.6
	ErrVariantAlsoNegotiates         = NewError(StatusVariantAlsoNegotiates)         // RFC 2295, 8.1
	ErrInsufficientStorage           = NewError(StatusInsufficientStorage)           // RFC 4918, 11.5
	ErrLoopDetected                  = NewError(StatusLoopDetected)                  // RFC 5842, 7.2
	ErrNotExtended                   = NewError(StatusNotExtended)                   // RFC 2774, 7
	ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // RFC 6585, 6
)

Errors

View Source
var (
	Events          = event.New()
	StatusCodePages = map[int]string{}
)
View Source
var AppMenus = []menu.Menu{}
View Source
var Arg args
View Source
var Cache cacheInterface = cache.New(1*time.Minute, 1*time.Second)
View Source
var Database *gorm.DB
View Source
var DefaultPath = map[string][]string{}
View Source
var Docs = []DocApp{}
View Source
var Exec string
View Source
var OS = struct {
	Name     string
	Version  string
	Kernel   string
	Username string
	Path     struct {
		Bin     []string
		Home    string
		Root    string
		Tmp     string
		AppData []string
	}
}{}
View Source
var ProcessID int
View Source
var WorkingDir string

Functions

func All

func All(path string, handlers ...func(request *Request))

All : https://fiber.wiki/application#http-methods

func Connect

func Connect(path string, handlers ...func(request *Request)) fiber.Router

Connect : https://fiber.wiki/application#http-methods

func CustomError

func CustomError(code int, path string) error

CustomError set custom page for errors

func Delete

func Delete(path string, handlers ...func(request *Request)) fiber.Router

Delete : https://fiber.wiki/application#http-methods

func Get

func Get(path string, handlers ...func(request *Request)) fiber.Router

Get : https://fiber.wiki/application#http-methods

func GetDBO

func GetDBO() *gorm.DB

GetDBO return database object instance

func GetFiber

func GetFiber() *fiber.App

GetFiber return fiber instance

func GetRegisteredApps

func GetRegisteredApps() map[string]interface{}

GetRegisteredApps return list of registered apps

func GetView

func GetView(prefix, name string) (*jet.Template, error)

GetView return view of given environment

func Group

func Group(path string, handlers ...func(request *Request)) group

Group is used for Routes with common prefix to define a new sub-router with optional middleware.

func GuessAsset

func GuessAsset(app App) string

func GuessPath

func GuessPath(file string) string

Guess path find file path from different locations

func Head(path string, handlers ...func(request *Request)) fiber.Router

Head : https://fiber.wiki/application#http-methods

func InitUserModel

func InitUserModel(database *gorm.DB, config interface{})

InitUserModel initialize the user model with given config

func NewDoc

func NewDoc(app App)

func Options

func Options(path string, handlers ...func(request *Request)) fiber.Router

Options : https://fiber.wiki/application#http-methods

func Pack

func Pack(path string)

func ParseArg

func ParseArg(dest interface{})

func ParseConfig

func ParseConfig(path string, key string, out interface{}) error

func Patch

func Patch(path string, handlers ...func(request *Request)) fiber.Router

Patch : https://fiber.wiki/application#http-methods

func Post

func Post(path string, handlers ...func(request *Request)) fiber.Router

Post : https://fiber.wiki/application#http-methods

func Put

func Put(path string, handlers ...func(request *Request)) fiber.Router

Put : https://fiber.wiki/application#http-methods

func Register

func Register(app App)

Register register app to use by EVO

func RegisterView

func RegisterView(prefix, path string) *jet.Set

RegisterView register views of given path

func Run

func Run()

Run start EVO Server

func SetCacheInterface added in v0.9.0

func SetCacheInterface(c cacheInterface)

func SetUserInterface

func SetUserInterface(p UserInterface)

func Setup

func Setup()

Setup setup the EVO app

func Shutdown

func Shutdown() error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil. Make sure the program doesn't exit and waits instead for Shutdown to return.

Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.

func Static

func Static(prefix, path string)

Static append path with given prefix to static files

func Trace

func Trace(path string, handlers ...func(request *Request)) fiber.Router

Trace : https://fiber.wiki/application#http-methods

func Use

func Use(path string, handler func(*Request) error) fiber.Router

Use registers a middleware route. Middleware matches requests beginning with the provided prefix. Providing a prefix is optional, it defaults to "/"

func Value added in v0.9.0

func Value(s string, params ...string) value

Types

type App

type App interface {
	Register()
	Router()
	WhenReady()
	Permissions() []Permission
	Pack()
	Menus() []menu.Menu
}

type Configuration

type Configuration struct {
	Log struct {
		WriteFile bool   `yaml:"writefile"`
		Path      string `yaml:"path"`
		Level     string `yaml:"level"`
	} `yaml:"log"`

	App struct {
		Name       string `yaml:"name"`
		Static     string `yaml:"static"`
		SessionAge int    `yaml:"session-age"`
		Language   string `yaml:"language"`
		StrongPass int    `yaml:"strong-pass-level"`
	} `yaml:"app"`

	JWT struct {
		Secret    string        `yaml:"secret"`
		Issuer    string        `yaml:"issuer"`
		Audience  []string      `yaml:"audience"`
		Age       time.Duration `yaml:"age"`
		Subject   string        `yaml:"subject"`
		AgeString string        `yaml:"age"`
	} `yaml:"jwt"`

	Server struct {
		Host          string `yaml:"host"`
		Port          string `yaml:"port"`
		Cert          string `yaml:"cert"`
		Key           string `yaml:"key"`
		HTTPS         bool   `yaml:"https"`
		Name          string `yaml:"name"`
		MaxUploadSize string `yaml:"max-upload-size"`
		StrictRouting bool   `yaml:"strict-routing"`
		CaseSensitive bool   `yaml:"case-sensitive"`
		RequestID     bool   `yaml:"request-id"`
		Debug         bool   `yaml:"debug"`
		Recover       bool   `yaml:"recover"`
	} `yaml:"server"`

	Database struct {
		Enabled        bool          `yaml:"enabled"`
		Type           string        `yaml:"type"`
		Username       string        `yaml:"user"`
		Password       string        `yaml:"pass"`
		Server         string        `yaml:"server"`
		Cache          string        `yaml:"cache"`
		CacheSize      string        `yaml:"cache-size"`
		Debug          string        `yaml:"debug"`
		Database       string        `yaml:"database"`
		SSLMode        string        `yaml:"ssl-mode"`
		Params         string        `yaml:"params"`
		MaxOpenConns   int           `yaml:"max-open-connections"`
		MaxIdleConns   int           `yaml:"max-idle-connections"`
		ConnMaxLifTime time.Duration `yaml:"connection-max-lifetime"`
	} `yaml:"database"`

	Tweaks struct {
		Ballast       bool   `yaml:"ballast"`
		BallastSize   string `yaml:"ballast-size"`
		MaxProcessors int    `yaml:"processors"`
		PreFork       bool   `yaml:"prefork"`
	} `yaml:"tweaks"`

	RateLimit struct {
		Enabled  bool `yaml:"enabled"`
		Duration int  `yaml:"duration"`
		Requests int  `yaml:"requests"`
	} `yaml:"ratelimit"`

	CORS struct {
		Enabled          bool     `yaml:"enabled"`
		AllowOrigins     string   `yaml:"allowed-origins"`
		AllowMethods     []string `yaml:"allowed-methods"`
		AllowHeaders     []string `yaml:"allowed-headers"`
		AllowCredentials bool     `yaml:"allowed-credentials"`
		MaxAge           int      `yaml:"requests"`
	} `yaml:"cors"`
}

func GetConfig

func GetConfig() *Configuration

GetConfig return configuration instance

type Cookie struct {
	Name     string    `json:"name"`
	Value    string    `json:"value"`
	Path     string    `json:"path"`
	Domain   string    `json:"domain"`
	Expires  time.Time `json:"expires"`
	Secure   bool      `json:"secure"`
	HTTPOnly bool      `json:"http_only"`
	SameSite string    `json:"same_site"`
}

Cookie data for ctx.Cookie

type DocAPI

type DocAPI struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Describe    []string `json:"describe"`
	Body        string   `json:"body"`
	Return      string   `json:"return"`
	Required    string   `json:"required"`
	Method      string   `json:"method"`
	URL         string   `json:"url"`
	Package     string   `json:"package"`
	Path        string   `json:"path"`
}

func (*DocAPI) Parse

func (obj *DocAPI) Parse(content []string, i int, meta map[string]string)

type DocApp

type DocApp struct {
	Name        string       `json:"name"`
	Description string       `json:"description"`
	Author      string       `json:"author"`
	Namespace   string       `json:"namespace"`
	Path        string       `json:"path"`
	Models      []*DocModel  `json:"models"`
	APIs        []*DocAPI    `json:"apis"`
	Permissions []Permission `json:"permissions"`
	Menus       []menu.Menu  `json:"menus"`
	Package     string       `json:"package"`
}

type DocModel

type DocModel struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"`
	Description string   `json:"description"`
	Methods     []string `json:"methods"`
	Fields      []string `json:"fields"`
	Package     string   `json:"package"`
	Path        string   `json:"path"`
}

func (*DocModel) Parse

func (obj *DocModel) Parse(content []string, i int, meta map[string]string)

type Error

type Error struct {
	Code    int
	Message string
}

func NewError

func NewError(code int, message ...string) *Error

NewError creates a new HTTPError instance.

type LocalUserImplementation

type LocalUserImplementation struct{}

func (LocalUserImplementation) AfterFind

func (p LocalUserImplementation) AfterFind(u *User) error

func (LocalUserImplementation) FromRequest

func (u LocalUserImplementation) FromRequest(r *Request)

SetGroup set user group

func (LocalUserImplementation) HasPerm

func (p LocalUserImplementation) HasPerm(u *User, v string) bool

func (LocalUserImplementation) HasRole

func (p LocalUserImplementation) HasRole(u *User, v interface{}) bool

func (LocalUserImplementation) Image

func (p LocalUserImplementation) Image(u *User) string

func (LocalUserImplementation) Save

func (p LocalUserImplementation) Save(u *User) error

func (LocalUserImplementation) SetGroup

func (p LocalUserImplementation) SetGroup(u *User, group interface{}) error

func (LocalUserImplementation) SetPassword

func (p LocalUserImplementation) SetPassword(u *User, password string) error

func (LocalUserImplementation) SyncPermissions

func (p LocalUserImplementation) SyncPermissions(app string, perms Permissions)

type Model

type Model struct {
	ID        uint       `json:"id" gorm:"primary_key"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `json:"deleted_at" sql:"index"`
}

type Permission

type Permission struct {
	Model
	CodeName    string `json:"code_name" form:"code_name" validate:"empty=false"`
	Title       string `json:"title" form:"title" validate:"empty=false"`
	Description string `json:"description" form:"description"`
	App         string `json:"app" form:"app" validate:"empty=false"`
}

Permission permission struct @doc type model

type Permissions

type Permissions []Permission

Permissions slice of permissions

func (Permissions) Sync

func (perms Permissions) Sync(app string)

Sync synchronize permissions on startup

type Request

type Request struct {
	Variables     fiber.Map
	Context       *fiber.Ctx
	JWT           *jwt.Payload
	Additional    interface{}
	User          *User
	Response      Response
	CacheKey      string
	CacheDuration time.Duration
	// contains filtered or unexported fields
}

func Upgrade

func Upgrade(ctx *fiber.Ctx) *Request

func (*Request) Accepts

func (r *Request) Accepts(offers ...string) (offer string)

Accepts checks if the specified extensions or content types are acceptable.

func (*Request) AcceptsCharsets

func (r *Request) AcceptsCharsets(offers ...string) (offer string)

AcceptsCharsets checks if the specified charset is acceptable.

func (*Request) AcceptsEncodings

func (r *Request) AcceptsEncodings(offers ...string) (offer string)

AcceptsEncodings checks if the specified encoding is acceptable.

func (*Request) AcceptsLanguages

func (r *Request) AcceptsLanguages(offers ...string) (offer string)

AcceptsLanguages checks if the specified language is acceptable.

func (*Request) Append

func (r *Request) Append(field string, values ...string)

Append the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.

func (*Request) Attachment

func (r *Request) Attachment(name ...string)

Attachment sets the HTTP response Content-Disposition header field to attachment.

func (*Request) BaseURL

func (r *Request) BaseURL() string

BaseURL returns (protocol + host).

func (*Request) Body

func (r *Request) Body() string

Body contains the raw body submitted in a POST request.

func (*Request) BodyParser

func (r *Request) BodyParser(out interface{}) error

BodyParser binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data

func (*Request) Cached added in v0.9.0

func (r *Request) Cached(duration time.Duration, key ...string) bool

func (*Request) ClearCookie

func (r *Request) ClearCookie(key ...string)

ClearCookie expires a specific cookie by key. If no key is provided it expires all cookies.

func (*Request) ContentType added in v0.9.2

func (r *Request) ContentType() string

ContentType returns request content type

func (*Request) Cookie

func (r *Request) Cookie(cookie *Cookie)

Cookie sets a cookie by passing a cookie struct

func (*Request) Cookies

func (r *Request) Cookies(key string) (value string)

Cookies is used for getting a cookie value by key

func (*Request) Download

func (r *Request) Download(file string, name ...string)

Download transfers the file from path as an attachment. Typically, browsers will prompt the user for download. By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog). Override this default with the filename parameter.

func (*Request) Flash

func (r *Request) Flash(params ...string)

func (*Request) FormFile

func (r *Request) FormFile(key string) (*multipart.FileHeader, error)

FormFile returns the first file by key from a MultipartForm.

func (*Request) FormValue

func (r *Request) FormValue(key string) (value string)

FormValue returns the first value by key from a MultipartForm.

func (*Request) FormValueI added in v0.9.0

func (r *Request) FormValueI(key string, params ...string) value

FormValue returns the first value by key from a MultipartForm.

func (*Request) Format

func (r *Request) Format(body interface{})

Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.

func (*Request) Fresh

func (r *Request) Fresh() bool

Fresh not implemented yet

func (*Request) Get

func (r *Request) Get(key string) string

Get returns the HTTP request header specified by field. Field names are case-insensitive

func (*Request) GetBrowser added in v0.9.2

func (r *Request) GetBrowser() *uasurfer.UserAgent

GetBrowser return browser information by parsing useragent

func (Request) GetFlashes

func (r Request) GetFlashes() []flash

func (*Request) GetI added in v0.9.0

func (r *Request) GetI(key string, params ...string) value

Get returns the HTTP request header specified by field. Field names are case-insensitive

func (*Request) HasError

func (r *Request) HasError() bool

func (*Request) Hostname

func (r *Request) Hostname() string

Hostname contains the hostname derived from the Host HTTP header.

func (*Request) IP

func (r *Request) IP() string

UserAgent returns request useragent

func (*Request) IPs

func (r *Request) IPs() []string

IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.

func (*Request) Is

func (r *Request) Is(extension string) (match bool)

Is returns the matching content type, if the incoming request’s Content-Type HTTP header field matches the MIME type specified by the type parameter

func (*Request) JSON

func (r *Request) JSON(data interface{}) error

JSON converts any interface or string to JSON using Jsoniter. This method also sets the content header to application/json.

func (*Request) JSONP

func (r *Request) JSONP(json interface{}, callback ...string) error

JSONP sends a JSON response with JSONP support. This method is identical to JSON, except that it opts-in to JSONP callback support. By default, the callback name is simply callback.

func (r *Request) Links(link ...string)

Links joins the links followed by the property to populate the response’s Link HTTP header field.

func (*Request) Locals

func (r *Request) Locals(key string, value ...interface{}) (val interface{})

Locals makes it possible to pass interface{} values under string keys scoped to the request and therefore available to all following routes that match the request.

func (*Request) Location

func (r *Request) Location(path string)

Location sets the response Location HTTP header to the specified path parameter.

func (*Request) Method

func (r *Request) Method(override ...string) string

Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.

func (*Request) MultipartForm

func (r *Request) MultipartForm() (*multipart.Form, error)

MultipartForm parse form entries from binary. This returns a map[string][]string, so given a key the value will be a string slice.

func (*Request) Next

func (r *Request) Next() error

Next executes the next method in the stack that matches the current route. You can pass an optional error for custom error handling.

func (*Request) OriginalURL

func (r *Request) OriginalURL() string

OriginalURL contains the original request URL.

func (*Request) Params

func (r *Request) Params(key string) string

Params is used to get the route parameters. Defaults to empty string "", if the param doesn't exist.

func (*Request) ParamsI added in v0.9.0

func (r *Request) ParamsI(key string, params ...string) value

Params is used to get the route parameters. Defaults to empty string "", if the param doesn't exist.

func (*Request) Path

func (r *Request) Path(override ...string) string

Path returns the path part of the request URL. Optionally, you could override the path.

func (*Request) Persist

func (r *Request) Persist()

func (*Request) Protocol

func (r *Request) Protocol() string

Protocol contains the request protocol string: http or https for TLS requests.

func (*Request) Query

func (r *Request) Query(key string) (value string)

Query returns the query string parameter in the url.

func (*Request) QueryI added in v0.9.0

func (r *Request) QueryI(key string, params ...string) value

Query returns the query string parameter in the url.

func (*Request) Redirect

func (r *Request) Redirect(path string, status ...int)

Redirect to the URL derived from the specified path, with specified status. If status is not specified, status defaults to 302 Found

func (*Request) Render

func (r *Request) Render(file string, bind interface{}) error

Render a template with data and sends a text/html response. We support the following engines: html, amber, handlebars, mustache, pug

func (*Request) RenderView

func (r *Request) RenderView(input interface{}, views ...string) *bytes.Buffer

func (*Request) SaveFile

func (r *Request) SaveFile(fileheader *multipart.FileHeader, path string) error

SaveFile saves any multipart file to disk.

func (*Request) Secure

func (r *Request) Secure() bool

Secure returns a boolean property, that is true, if a TLS connection is established.

func (*Request) Send

func (r *Request) Send(body string)

Send sets the HTTP response body. The Send body can be of any type.

func (*Request) SendBytes

func (r *Request) SendBytes(body []byte)

SendBytes sets the HTTP response body for []byte types This means no type assertion, recommended for faster performance

func (*Request) SendFile

func (r *Request) SendFile(file string, noCompression ...bool)

SendFile transfers the file from the given path. The file is compressed by default Sets the Content-Type response HTTP header field based on the filenames extension.

func (*Request) SendHTML

func (r *Request) SendHTML(body interface{})

Send sets the HTML response body. The Send body can be of any type.

func (*Request) SendStatus

func (r *Request) SendStatus(status int)

SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

func (*Request) SendString

func (r *Request) SendString(body string)

SendString sets the HTTP response body for string types This means no type assertion, recommended for faster performance

func (*Request) Set

func (r *Request) Set(key string, val string)

Set sets the response’s HTTP header field to the specified key, value.

func (*Request) SetCookie

func (r *Request) SetCookie(key string, val interface{}, params ...interface{})

SetCookie set cookie with given name,value and optional params (wise function)

func (*Request) SetError

func (r *Request) SetError(err interface{})

func (*Request) Stale

func (r *Request) Stale() bool

Stale is not implemented yet, pull requests are welcome!

func (*Request) Status

func (r *Request) Status(status int) *Request

Status sets the HTTP status for the response. This method is chainable.

func (*Request) Subdomains

func (r *Request) Subdomains(offset ...int) []string

Subdomains returns a string slive of subdomains in the domain name of the request. The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.

func (*Request) Throw

func (r *Request) Throw(e *e.Error)

func (*Request) Type

func (r *Request) Type(ext string) *Request

Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

func (*Request) URL

func (r *Request) URL() *URL

func (*Request) Unauthorized

func (r *Request) Unauthorized() bool

func (*Request) UserAgent added in v0.9.2

func (r *Request) UserAgent() string

UserAgent returns request useragent

func (*Request) Var

func (r *Request) Var(key string, value interface{})

func (*Request) Vary

func (r *Request) Vary(fields ...string)

Vary adds the given header field to the Vary response header. This will append the header, if not already listed, otherwise leaves it listed in the current location.

func (*Request) View

func (r *Request) View(data interface{}, views ...string)

func (*Request) Write

func (r *Request) Write(body interface{})

Write appends any input to the HTTP body response.

func (*Request) WriteResponse

func (r *Request) WriteResponse(resp ...interface{})

func (*Request) XHR

func (r *Request) XHR() bool

XHR returns a Boolean property, that is true, if the request’s X-Requested-With header field is XMLHttpRequest, indicating that the request was issued by a client library (such as jQuery).

type Response

type Response struct {
	Success bool        `json:"success"`
	Message string      `json:"message"`
	Error   e.Errors    `json:"errors"`
	Data    interface{} `json:"data"`
	Code    int         `json:"code"`
}

func (Response) HasError

func (response Response) HasError() bool

type Role

type Role struct {
	Model
	Name          string       `json:"name" form:"name" validate:"empty=false & format=strict_html"`
	CodeName      string       `json:"code_name" json:"code_name" validate:"empty=false & format=slug" gorm:"type:varchar(100);unique_index"`
	Parent        uint         `json:"parent" form:"parent"`
	Groups        []*UserGroup `json:"-" gorm:"many2many:group_roles;"`
	Permission    *Permissions `json:"permissions_data" gorm:"-"  validate:"-"`
	PermissionSet []string     `json:"permissions" form:"permissions" gorm:"-"`
}

Role role struct @doc type model

func (*Role) AfterFind

func (r *Role) AfterFind(tx *gorm.DB) (err error)

AfterFind after find event

func (*Role) HasPerm

func (r *Role) HasPerm(v string) bool

HasPerm check if role has permission

func (*Role) Save

func (r *Role) Save() error

Save save role instance

func (*Role) SetPermission

func (r *Role) SetPermission(permissions Permissions) error

SetPermission set role permission

func (Role) TableName

func (Role) TableName() string

TableName return role model table name

type RolePermission

type RolePermission struct {
	Model
	RoleID       uint
	PermissionID uint
}

RolePermission role to permission orm @doc type model

type URL

type URL struct {
	Query  url.Values
	Host   string
	Scheme string
	Path   string
	Raw    string
}

func (*URL) Set

func (u *URL) Set(key string, value interface{}) *URL

func (*URL) String

func (u *URL) String() string

type User

type User struct {
	Model
	GivenName  string     `json:"given_name" form:"given_name" mapstructure:"given_name"`
	FamilyName string     `json:"family_name" form:"family_name" mapstructure:"family_name"`
	Username   string     `` /* 145-byte string literal not displayed */
	Password   string     `json:"-" form:"-" validate:"empty=false & format=strict_html"`
	Email      string     `json:"email" form:"email" mapstructure:"email" validate:"empty=false & format=email" gorm:"type:varchar(32);unique_index"`
	Roles      []*Role    `json:"roles" form:"roles"  validate:"-"`
	Group      *UserGroup `json:"-" form:"-" gorm:"-"  validate:"-"`
	GroupID    uint       `json:"group_id" form:"group_id"`
	Anonymous  bool       `json:"anonymous" form:"anonymous" gorm:"-"`
	Active     bool       `json:"active" form:"active"`
	Seen       time.Time  `json:"seen" form:"seen"`
	Admin      bool       `json:"admin" form:"admin"`
	Params     data.Map   `gorm:"type:json" mapstructure:"-" form:"params" json:"params"`
}

User user struct @doc type model

func (*User) AfterFind

func (u *User) AfterFind(tx *gorm.DB) (err error)

AfterFind after find event

func (*User) FromRequest

func (u *User) FromRequest(r *Request)

SetGroup set user group

func (*User) HasPerm

func (u *User) HasPerm(v string) bool

HasPerm check if user has permission

func (*User) HasRole

func (u *User) HasRole(v interface{}) bool

HasRole check if user has role

func (*User) Image

func (u *User) Image() string

Image return user image

func (*User) ParseParams

func (u *User) ParseParams(out interface{}) error

TODO: parse using reflect Save save user instance

func (*User) Save

func (u *User) Save() error

Save save user instance

func (*User) SetGroup

func (u *User) SetGroup(group interface{}) error

SetGroup set user group

func (*User) SetPassword

func (u *User) SetPassword(password string) error

SetPassword set user password

type UserGroup

type UserGroup struct {
	Model
	Name     string   `json:"name" form:"name" validate:"empty=false & format=strict_html"`
	CodeName string   `json:"code_name" json:"code_name" validate:"empty=false & format=slug" gorm:"type:varchar(100);unique_index"`
	Parent   uint     `json:"parent" form:"parent"`
	Roles    []*Role  `json:"roles_data" gorm:"many2many:group_roles;" validate:"-"`
	RoleSet  []string `json:"roles" form:"roles" gorm:"-"`
}

Group group struct @doc type model

func (*UserGroup) AfterFind

func (g *UserGroup) AfterFind(tx *gorm.DB) (err error)

AfterFind after find event

func (*UserGroup) HasPerm

func (g *UserGroup) HasPerm(v string) bool

HasPerm check the group if has permission

func (*UserGroup) Save

func (g *UserGroup) Save() error

Save save the group instance

func (UserGroup) TableName

func (UserGroup) TableName() string

TableName return group model table name

type UserInterface

type UserInterface interface {
	Save(u *User) error
	HasPerm(u *User, v string) bool
	HasRole(u *User, v interface{}) bool
	Image(u *User) string
	SetPassword(u *User, password string) error
	SetGroup(u *User, group interface{}) error
	AfterFind(u *User) error
	SyncPermissions(app string, permissions Permissions)
	FromRequest(r *Request)
}

Directories

Path Synopsis
apps
auth
@doc type app @doc name auth @doc description authentication api @doc author reza @doc include github.com/getevo/evo/user.model.go
@doc type app @doc name auth @doc description authentication api @doc author reza @doc include github.com/getevo/evo/user.model.go
rdb
cmd
evo
lib
T
cli
Package cli provides a minimal framework for creating and organizing command line Go applications.
Package cli provides a minimal framework for creating and organizing command line Go applications.
conv/internal/convert
Package convert contains common conversion interfaces.
Package convert contains common conversion interfaces.
conv/internal/refconv
Package refconv implements the Converter interface by using the standard libraries reflection package.
Package refconv implements the Converter interface by using the standard libraries reflection package.
is
jwt
Package jwt is a JSON Web Token signer, verifier and validator.
Package jwt is a JSON Web Token signer, verifier and validator.
log
ref
try
validate
Package validate validates Go structs and types recursively based on tags.
Package validate validates Go structs and types recursively based on tags.

Jump to

Keyboard shortcuts

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