gramework

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2022 License: Apache-2.0 Imports: 42 Imported by: 6

Documentation

Index

Constants

View Source
const (
	// MethodDELETE is the HTTP DELETE method
	MethodDELETE = "DELETE"

	// MethodGET is the HTTP GET method
	MethodGET = "GET"

	// MethodHEAD is the HTTP HEAD method
	MethodHEAD = "HEAD"

	// MethodOPTIONS is the HTTP OPTIONS method
	MethodOPTIONS = "OPTIONS"

	// MethodPATCH is the HTTP PATCH method
	MethodPATCH = "PATCH"

	// MethodPOST is the HTTP POST method
	MethodPOST = "POST"

	// MethodPUT is the HTTP PUT method
	MethodPUT = "PUT"
)
View Source
const (
	// GET method
	GET = "GET"
	// HEAD method
	HEAD = "HEAD"
	// OPTIONS method
	OPTIONS = "OPTIONS"
	// POST method
	POST = "POST"
	// PUT method
	PUT = "PUT"
	// PATCH method
	PATCH = "PATCH"
	// DELETE method
	DELETE = "DELETE"
	// CONNECT method
	CONNECT = "CONNECT"

	// PathAny used to minimize memory allocations
	PathAny = "*"
	// PathSlashAny used to minimize memory allocations
	PathSlashAny = "/*"
	// PathSlash used to minimize memory allocations
	PathSlash = "/"

	// HeaderAllow used to minimize memory allocations
	HeaderAllow = "Allow"
)
View Source
const (
	Version        = "1.8.0"
	DefaultAppName = "gramework/" + Version
)

Version gives you the gramework version you use now

View Source
const (

	// ContextKey defines where in context.Context will be stored gramework.Context for current request
	ContextKey contextKey = "gramework:request:ctx"
)
View Source
const Slash = "/"

Slash constant used to minimize string allocations

Variables

View Source
var (
	// ErrTLSNoEmails occurs when no emails provided but user tries to use AutoTLS features
	ErrTLSNoEmails = errors.New("auto tls: no emails provided")

	// ErrArgNotFound used when no route argument is found
	ErrArgNotFound = errors.New("undefined argument")

	// ErrInvalidGQLRequest used in DecodeGQL
	ErrInvalidGQLRequest = errors.New("invalid gql request")
)
View Source
var (
	// DefaultContentType cached to minimize memory allocations
	DefaultContentType = []byte("text/plain; charset=utf-8")
	// QuestionMark cached to minimize memory allocations
	QuestionMark = []byte("?")

	// SlashByte cached to minimize memory allocations
	SlashByte = byte('/')
)
View Source
var (
	// ErrEmptyMiddleware can be returned by App.Use*, if middleware is nil
	ErrEmptyMiddleware = errors.New("can't use nil middleware")

	// ErrUnsupportedMiddlewareType can be returned by App.Use*, if middleware type is unsupported
	ErrUnsupportedMiddlewareType = errors.New("unsupported middleware type")
)
View Source
var Logger = &log.Logger{
	Level:   log.InfoLevel,
	Handler: cli.New(os.Stdout),
}

Logger handles default logger

Functions

func BytesToString added in v1.1.0

func BytesToString(b []byte) string

BytesToString effectively converts bytes to string nolint: gas

func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func DefaultPanicHandler added in v1.1.0

func DefaultPanicHandler(ctx *Context, panicReason interface{})

DefaultPanicHandler serves error page or error response depending on ctx.ContentType()

func DisableFlags added in v1.1.0

func DisableFlags()

DisableFlags globally disables default flags. Useful when using non-default flag libraries like pflag.

func Errorf

func Errorf(msg string, v ...interface{})

Errorf logs an error using default logger

func Nanotime

func Nanotime() int64

Nanotime is monotonic time provider.

func OptAppName added in v1.4.0

func OptAppName(n string) func(*App)

OptAppName sets app.name and app.serverBase.Name

func OptKeepHijackedConns added in v1.7.0

func OptKeepHijackedConns(keep bool) func(*App)

OptKeepHijackedConns sets new KeepHijackedConns in the server used at the execution time. All OptUseServer will overwrite this setting 'case OptUseServer replaces the whole server instance with a new one.

func OptMaxRequestBodySize added in v1.1.0

func OptMaxRequestBodySize(size int) func(*App)

OptMaxRequestBodySize sets new MaxRequestBodySize in the server used at the execution time. All OptUseServer will overwrite this setting 'case OptUseServer replaces the whole server instance with a new one.

func OptUseCustomLogger added in v1.7.0

func OptUseCustomLogger(logger *log.Logger) func(*App)

OptUseCustomLogger allows use custom preconfigured Apex logger. For exmaple with custom Handler.

func OptUseServer added in v1.1.0

func OptUseServer(s *fasthttp.Server) func(*App)

OptUseServer sets fasthttp.Server instance to use

func SetEnv added in v1.1.0

func SetEnv(e Environment)

SetEnv sets gramework's environment

func SetInternalLogger added in v1.7.1

func SetInternalLogger(log log.Interface)

SetInternalLogger allows to change internal log used for handler registration logs etc.

func StringToBytes added in v1.1.0

func StringToBytes(s string) []byte

StringToBytes effectively converts string to bytes nolint: gas

func TicksPerSecond added in v1.2.0

func TicksPerSecond() int64

TicksPerSecond reports cpu ticks per second counter

func UnJSONBytes

func UnJSONBytes(b []byte, v ...interface{}) (interface{}, error)

UnJSONBytes deserializes JSON request body to given variable pointer or allocates a new one. Returns resulting data and error. One of them may be nil.

Types

type App

type App struct {
	Flags *Flags

	Logger log.Interface

	Settings  Settings
	TLSEmails []string
	TLSPort   uint16

	EnableFirewall bool

	HandleUnknownDomains bool

	NoDefaultPanicHandler    bool
	PanicHandlerNoPoweredBy  bool
	PanicHandlerCustomLayout string

	DefaultCacheOptions *CacheOptions
	// contains filtered or unexported fields
}

App represents a gramework app

func New

func New(opts ...func(*App)) *App

New App

func (*App) AddFlag

func (app *App) AddFlag(f Flag)

AddFlag adds a Flag to flag queue that will be parsed if flags wasn't parsed yet

func (*App) Behind added in v1.7.0

func (app *App) Behind(u Behind)

func (*App) Blacklist added in v1.1.0

func (app *App) Blacklist(ip net.IP) (ok bool)

Blacklist adds given ip to untrustedIP list, if it is not whitelisted. Any ip blacklisted with Gramework Protection can't access protected enpoints via any method.

See also App.Protect(), App.Whitelist(), App.Untrust(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*App) CORSMiddleware

func (app *App) CORSMiddleware(domains ...string) func(*Context)

CORSMiddleware provides gramework handler with ctx.CORS() call

func (*App) DELETE

func (app *App) DELETE(route string, handler interface{}) *App

DELETE registers a handler for a DELETE request to the given route

func (*App) Domain

func (app *App) Domain(domain string) *Router

Domain returns a domain router

func (*App) Forbidden

func (app *App) Forbidden(ctx *Context)

Forbidden send 403 Forbidden error

func (*App) GET

func (app *App) GET(route string, handler interface{}) *App

GET registers a handler for a GET request to the given route

func (*App) GetStringFlag added in v1.1.0

func (app *App) GetStringFlag(name string) (string, bool)

GetStringFlag return command line app flag value by name and false if not exists

func (*App) HEAD

func (app *App) HEAD(route string, handler interface{}) *App

HEAD registers a handler for a HEAD request to the given route

func (*App) HTTP

func (app *App) HTTP() *Router

HTTP returns HTTP-only router

func (*App) HTTPS

func (app *App) HTTPS() *Router

HTTPS returns HTTPS-only router

func (*App) Handle

func (app *App) Handle(method, route string, handler interface{}) *App

Handle registers a new request handle with the given path and method. For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used. This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*App) HandleMethodNotAllowed

func (app *App) HandleMethodNotAllowed(newValue bool) (oldValue bool)

HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router

func (*App) HandleOPTIONS

func (app *App) HandleOPTIONS(newValue bool) (oldValue bool)

HandleOPTIONS changes HandleOPTIONS mode in the router

func (*App) Health

func (app *App) Health()

Health registers HealthHandler on /internal/health

func (*App) HealthHandler

func (app *App) HealthHandler(ctx *Context)

HealthHandler serves info about memory usage

func (*App) JSON

func (app *App) JSON(route string, handler interface{}) *App

JSON register internal handler that sets json content type and serves given handler with GET method

func (*App) ListenAndServe

func (app *App) ListenAndServe(addr ...string) error

ListenAndServe HTTP on given addr. runs flag.Parse() if !flag.Parsed() to support --bind flag.

func (*App) ListenAndServeAll

func (app *App) ListenAndServeAll(httpAddr ...string)

ListenAndServeAll serves HTTP and HTTPS automatically. HTTPS is served on :443. If it can't serve http or https, it logs an error and exit the server with app.Logger.Fatalf().

func (*App) ListenAndServeAllDev

func (app *App) ListenAndServeAllDev(httpAddr ...string)

ListenAndServeAllDev serves HTTP and HTTPS automatically with localhost HTTPS support via self-signed certs. HTTPS is served on :443. If it can't serve http or https, it logs an error and exit the server with app.Logger.Fatalf(). Deprecated: Use ListenAndServeAll() instead

func (*App) ListenAndServeAutoTLS

func (app *App) ListenAndServeAutoTLS(addr string, cachePath ...string) error

ListenAndServeAutoTLS serves TLS requests

func (*App) ListenAndServeAutoTLSDev

func (app *App) ListenAndServeAutoTLSDev(addr string, cachePath ...string) error

ListenAndServeAutoTLSDev serves non-production grade TLS requests. Supports localhost.localdomain. Deprecated: use ListenAndServeAutoTLS() instead

func (*App) MaxHackAttempts added in v1.1.0

func (app *App) MaxHackAttempts(attempts int32) (oldValue int32)

MaxHackAttempts sets new max hack attempts for blacklist triggering in the Gramework Protection. If 0 passed, MaxHackAttempts just returns current value without setting a new one. If -1 passed, automatic blacklist disabled. This function is threadsafe and atomic.

See `ctx.Whitelist()`, `ctx.Blacklist()` and `ctx.Suspect()` for manual Gramework Protection control.

See also App.Protect(), App.Whitelist(), App.Blacklist(), App.Suspect(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*App) MethodNotAllowed

func (app *App) MethodNotAllowed(c func(ctx *Context)) *App

MethodNotAllowed sets MethodNotAllowed handler

func (*App) NotFound

func (app *App) NotFound(notFoundHandler func(*Context)) *App

NotFound set a handler which is called when no matching route is found

func (*App) OPTIONS

func (app *App) OPTIONS(route string, handler interface{}) *App

OPTIONS registers a handler for a OPTIONS request to the given route

func (*App) PATCH

func (app *App) PATCH(route string, handler interface{}) *App

PATCH registers a handler for a PATCH request to the given route

func (*App) POST

func (app *App) POST(route string, handler interface{}) *App

POST registers a handler for a POST request to the given route

func (*App) PUT

func (app *App) PUT(route string, handler interface{}) *App

PUT registers a handler for a PUT request to the given route

func (*App) PanicHandler

func (app *App) PanicHandler(panicHandler func(*Context, interface{})) *App

PanicHandler set a handler for unhandled panics

func (*App) Protect added in v1.1.0

func (app *App) Protect(endpointPrefix string)

Protect enables Gramework Protection for routes registered after Protect() call.

Protects all routes, that prefixed with given enpointPrefix. For example:

app := gramework.New()
app.GET("/internal/status", serveStatus) // will **not be** protected, .Protected() isn't called yet
app.Protect("/internal")
registerYourInternalRoutes(app.Sub("/internal")) // all routes here will be protected

Any blacklisted ip can't access protected enpoints via any method. Blacklist can work automatically, manually or both. To disable automatic blacklist do App.MaxHackAttemts(-1). Automatic blacklist bans suspected IP after App.MaxHackAttempts(). This behaviour is disabled for whitelisted ip.

See also App.Whitelist(), App.Untrust(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*App) Redir

func (app *App) Redir(url string) func(*Context)

Redir sends 301 redirect to the given url

it's equivalent to

ctx.Redirect(url, 301)

func (*App) RegFlags

func (app *App) RegFlags()

RegFlags registers current flag queue in flag parser

func (*App) SPAIndex

func (app *App) SPAIndex(pathOrHandler interface{}) *Router

SPAIndex serves an index file or handler on any unregistered route

func (*App) Serve

func (app *App) Serve(ln net.Listener) error

Serve app on given listener

func (*App) ServeDir

func (app *App) ServeDir(path string) func(*Context)

ServeDir from a given path

func (*App) ServeDirCustom

func (app *App) ServeDirCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) func(*Context)

ServeDirCustom gives you ability to serve a dir with custom settings

func (*App) ServeDirNoCache

func (app *App) ServeDirNoCache(path string) func(*Context)

ServeDirNoCache gives you ability to serve a dir without caching

func (*App) ServeDirNoCacheCustom

func (app *App) ServeDirNoCacheCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) func(*Context)

ServeDirNoCacheCustom gives you ability to serve a dir with custom settings without caching

func (*App) ServeFile

func (app *App) ServeFile(route, file string) *Router

ServeFile serves a file on a given route

func (*App) ServeInfrastructure deprecated

func (app *App) ServeInfrastructure(i *infrastructure.Infrastructure)

ServeInfrastructure serves Infrastructure info It's an integration of our module

Deprecated: will be moved to another package

func (*App) SetCookieDomain added in v1.1.0

func (app *App) SetCookieDomain(domain string)

SetCookieDomain allows you to implement SSO and other useful features without additional pain

func (*App) SetCookieExpire added in v1.2.1

func (app *App) SetCookieExpire(d time.Duration)

SetCookieExpire allows you set cookie expire time

func (*App) SetCookiePath added in v1.2.2

func (app *App) SetCookiePath(path string)

SetCookiePath allows you set cookie path

func (*App) SetName added in v1.1.0

func (app *App) SetName(name string)

SetName for the server Deprecated: Use New() with OptAppName option instead

func (*App) SetSanitizerPolicy added in v1.7.0

func (app *App) SetSanitizerPolicy(newPolicy *bluemonday.Policy)

SetSanitizerPolicy updates app's sanitizer policy to a new one, if newPolicy is not nil

func (*App) Shutdown added in v1.1.0

func (app *App) Shutdown() (err error)

Shutdown gracefully shuts down application servers

func (*App) Sub

func (app *App) Sub(path string) *SubRouter

Sub let you quickly register subroutes with given prefix like app.Sub("/v1").Sub("/users").GET("/view/:id", "hi").DELETE("/delete/:id", "hi"), that give you /v1/users/view/:id and /v1/users/delete/:id registered

func (*App) Suspect added in v1.1.0

func (app *App) Suspect(ip net.IP) (ok bool)

Suspect adds given ip to Gramework Protection suspectedIP list.

See also App.Protect(), App.Untrust(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*App) ToTLSHandler

func (app *App) ToTLSHandler() func(*Context)

ToTLSHandler returns handler that redirects user to HTTPS scheme

func (*App) Untrust added in v1.1.0

func (app *App) Untrust(ip net.IP) (ok bool)

Untrust removes given ip from trustedIP list, that enables protection of Gramework Protection enabled endpoints for given ip too. Opposite of App.Whitelist().

See also App.Protect(), App.Whitelist(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*App) Use

func (app *App) Use(middleware interface{}) error

Use the middleware before request processing

func (*App) UseAfterRequest

func (app *App) UseAfterRequest(middleware interface{}) error

UseAfterRequest the middleware after request processing

func (*App) UsePre

func (app *App) UsePre(middleware interface{}) error

UsePre registers middleware before any other middleware. Use only for metrics or access control!

func (*App) Whitelist added in v1.1.0

func (app *App) Whitelist(ip net.IP) (ok bool)

Whitelist adds given ip to Gramework Protection trustedIP list. To remove IP from whitelist, call App.Untrust()

See also App.Protect(), App.Untrust(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

type Auth added in v1.1.0

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

Auth is a struct that handles context's basic auth features

func (*Auth) GetLogin added in v1.1.0

func (a *Auth) GetLogin() (string, error)

GetLogin lazy triggers parser and returns login or an error. Error will be persistent for current context

Common typos: GetUser, GetUsername

func (*Auth) GetPass added in v1.1.0

func (a *Auth) GetPass() (string, error)

GetPass lazy triggers parser and returns password or an error. Error will be persistent for current context

Common typos: GetPassword

type Behind added in v1.7.0

type Behind interface {
	RemoteIP(ctx *Context) net.IP
	RemoteAddr(ctx *Context) net.Addr
}

Behind is an interface that allow you to parse provider-dependent headers in a compatible way.

WARNING: this interface is currently in a WIP state and unfrozen. If you want to support your provider, please open an issue or PR at https://github.com/gramework/gramework. In that way we can ensure that you have always working implementation.

type CacheOptions added in v1.7.0

type CacheOptions struct {
	// TTL is the time that cached response is valid
	TTL time.Duration
	// Cacheable function returns if current request is cacheable.
	// By deafult, any request with Authentication header or any Cookies will not be cached for security reasons.
	// If you want to cache responses for authorized users, please replace both Cacheable and CacheKey functions
	// to make sure that CacheKey includes something like session id.
	Cacheable func(ctx *Context) bool
	// CacheKey function returns the cache key for current request
	CacheKey func(ctx *Context) []byte

	// ReadCache allows for cache engine replacement. By default, gramework uses github.com/VictoriaMetrics/fastcache.
	// ReadCache returns the value and boolean if the value was found and still valid.
	ReadCache func(ctx *Context, key []byte) ([]byte, bool)
	// StoreCache allows for cache engine replacement. By default, gramework uses github.com/VictoriaMetrics/fastcache.
	StoreCache func(ctx *Context, key, value []byte, ttl time.Duration)

	// CacheableHeaders is a list of headers that gramework can cache.
	// Note, that if X-ABC is present both in cacheable and noncacheable header lists,
	// it will not be cached.
	CacheableHeaders []string // slice of canonical header names
	// NonCacheableHeaders is a list of headers that gramework can not cache.
	// Note, that if X-ABC is present both in cacheable and noncacheable header lists,
	// it will not be cached.
	NonCacheableHeaders []string
}

CacheOptions is a handler cache configuration structure.

type Context

type Context struct {
	*fasthttp.RequestCtx

	Logger log.Interface
	App    *App

	Cookies Cookies
	// contains filtered or unexported fields
}

Context is a gramework request context

func ContextFromValue added in v1.1.0

func ContextFromValue(ctx context.Context) *Context

ContextFromValue returns gramework.Context from context.Context value from gramework.ContextKey in a more effective way, than standard eface.(*SomeType). WARNING: this function may return nil, if ctx has no gramework.Context stored or ctx is nil. This function will give a warning if you call it with nil context.Context.

func (*Context) Auth added in v1.1.0

func (ctx *Context) Auth() *Auth

Auth returns struct for simple basic auth handling

useful to develop e.g. stage environment login, where high security is not required

func (*Context) BadRequest added in v1.1.0

func (ctx *Context) BadRequest(err ...error)

BadRequest sends HTTP/1.1 400 Bad Request

func (*Context) Blacklist added in v1.1.0

func (ctx *Context) Blacklist() (ok bool)

Blacklist adds given ip to untrustedIP list, if it is not whitelisted. Any blacklisted ip can't access protected enpoints via any method.

See also App.Protect(), App.Whitelist(), App.Untrust(), App.Suspect(), App.MaxHackAttempts(), App.Blacklist(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*Context) CORS

func (ctx *Context) CORS(domains ...string) *Context

CORS enables CORS in the current context

func (*Context) CSV added in v1.1.0

func (ctx *Context) CSV(v interface{}) error

CSV sends text/csv content type (see rfc4180, sec 3) and csv-encoded value to client

func (*Context) ContentType added in v1.1.0

func (ctx *Context) ContentType() string

ContentType returns Content-Type header for current request

func (*Context) DecodeGQL added in v1.1.0

func (ctx *Context) DecodeGQL() (*GQLRequest, error)

DecodeGQL parses GraphQL request and returns data from it

func (*Context) Encode added in v1.1.0

func (ctx *Context) Encode(v interface{}) (string, error)

Encode automatically determines accepted formats and choose preferred one

func (*Context) Err500

func (ctx *Context) Err500(message ...interface{}) *Context

Err500 sets Internal Server Error status

func (*Context) Forbidden

func (ctx *Context) Forbidden()

Forbidden send 403 Forbidden error

func (*Context) GETKeys

func (ctx *Context) GETKeys() []string

GETKeys returns GET parameters keys (query args)

func (*Context) GETKeysBytes

func (ctx *Context) GETKeysBytes() [][]byte

GETKeysBytes returns GET parameters keys (query args) as []byte

func (*Context) GETParam

func (ctx *Context) GETParam(argName string) []string

GETParam returns GET parameter (query arg) by name

func (*Context) GETParams

func (ctx *Context) GETParams() map[string][]string

GETParams returns GET parameters (query args)

func (*Context) GetCookieDomain added in v1.1.0

func (ctx *Context) GetCookieDomain() (domain string, wasConfigured bool)

GetCookieDomain returns previously configured cookie domain and if cookie domain was configured at all

func (*Context) HTML

func (ctx *Context) HTML(src ...string) *Context

HTML sets HTML content type

func (*Context) HackAttemptDetected added in v1.1.0

func (ctx *Context) HackAttemptDetected()

HackAttemptDetected adds given ip to Gramework Protection suspectedIP list. Use it when you detected app-level hack attempt from current client.

See also App.Protect(), App.Whitelist(), App.Untrust(), App.Suspect(), App.MaxHackAttempts(), App.Blacklist(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Suspect(), Context.Blacklist(), Context.SuspectsHackAttempts()

func (*Context) IsBlacklisted added in v1.1.0

func (ctx *Context) IsBlacklisted() (isBlacklisted bool)

IsBlacklisted checks if we have current client in Gramework Protection untrustedIP list. Use ctx.Blacklist() to add current client to untrustedIP list.

See also App.Protect(), App.Whitelist(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*Context) IsSuspect added in v1.1.0

func (ctx *Context) IsSuspect() (isSuspect bool)

IsSuspect checks if we have current client in Gramework Protection suspectedIP list. Use ctx.Suspect() to add current client to suspectedIP list.

See also App.Protect(), App.Whitelist(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*Context) IsWhitelisted added in v1.1.0

func (ctx *Context) IsWhitelisted() (isWhitelisted bool)

IsWhitelisted checks if we have current client in Gramework Protection trustedIP list. Use ctx.Whitelist() to add current client to trusted list.

See also App.Protect(), App.Whitelist(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*Context) JSON

func (ctx *Context) JSON(v interface{}) error

JSON serializes and writes a json-formatted response to user

func (*Context) JSONError

func (ctx *Context) JSONError(v interface{}) error

JSONError sets Internal Server Error status, serializes and writes a json-formatted response to user

func (*Context) LogHeaders

func (ctx *Context) LogHeaders()

LogHeaders logs all request headers for debug

func (*Context) MWKill added in v1.1.0

func (ctx *Context) MWKill()

MWKill kills current context and stop any user-defined processing. This function intented for use in middlewares.

func (*Context) Proxy

func (ctx *Context) Proxy(url string) (err error)

Proxy request to given url

func (*Context) RemoteAddr added in v1.7.0

func (ctx *Context) RemoteAddr() net.Addr

func (*Context) RemoteIP added in v1.7.0

func (ctx *Context) RemoteIP() net.IP

func (*Context) RequestID added in v1.1.0

func (ctx *Context) RequestID() string

RequestID return request ID for current context's request

func (*Context) RouteArg

func (ctx *Context) RouteArg(argName string) string

RouteArg returns an argument value as a string or empty string

func (*Context) RouteArgErr

func (ctx *Context) RouteArgErr(argName string) (string, error)

RouteArgErr returns an argument value as a string or empty string and ErrArgNotFound if argument was not found

func (*Context) Sanitize added in v1.7.0

func (ctx *Context) Sanitize(s string) string

Sanitize returns a sanitized `s`. It use bluemonday to sanitize given parameter.

To change sanitizer policy, see (*App).SetSanitizerPolicy.

func (*Context) Sanitizer added in v1.7.0

func (ctx *Context) Sanitizer() *bluemonday.Policy

Sanitizer returns current bluemonday policy.

To change sanitizer policy, see (*App).SetSanitizerPolicy.

Context must not update the policy at runtime. Instead, please use a new policy.

func (*Context) SubPrefixes added in v1.1.0

func (ctx *Context) SubPrefixes() []string

SubPrefixes returns list of router's prefixes that was created using .Sub() feature

func (*Context) Suspect added in v1.1.0

func (ctx *Context) Suspect() (ok bool)

Suspect adds current client ip to Gramework Protection suspectedIP list.

See also App.Protect(), App.Untrust(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*Context) SuspectsHackAttempts added in v1.1.0

func (ctx *Context) SuspectsHackAttempts() (attempts int32)

SuspectsHackAttempts returns hack attempts detected with Gramework Protection both automatically and manually by calling Context.HackAttemptDetected(). For any whitelisted ip this function will return 0.

See also App.Protect(), App.Whitelist(), App.Untrust(), App.Suspect(), App.MaxHackAttempts(), App.Blacklist(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Suspect(), Context.Blacklist(), Context.HackAttemptDetected()

func (*Context) ToCSV added in v1.1.0

func (ctx *Context) ToCSV(v interface{}) ([]byte, error)

ToCSV encodes csv-encoded value to client

func (*Context) ToContext added in v1.1.0

func (ctx *Context) ToContext(parentCtx ...context.Context) context.Context

ToContext returns context.Context with gramework.Context stored in context values as a pointer (see gramework.ContextKey to receive and use this value).

By default this func will extend context.Background(), if parentCtx is not provided.

func (*Context) ToJSON

func (ctx *Context) ToJSON(v interface{}) ([]byte, error)

ToJSON serializes v and returns the result

func (*Context) ToTLS

func (ctx *Context) ToTLS()

ToTLS redirects user to HTTPS scheme

func (*Context) ToXML added in v1.1.0

func (ctx *Context) ToXML(v interface{}) ([]byte, error)

ToXML encodes xml-encoded value to client

func (*Context) UnJSON

func (ctx *Context) UnJSON(v interface{}) error

UnJSON deserializes JSON request body to given variable pointer

func (*Context) UnJSONBytes

func (ctx *Context) UnJSONBytes(b []byte, v ...interface{}) (interface{}, error)

UnJSONBytes deserializes JSON request body to given variable pointer or allocates a new one. Returns resulting data and error. One of them may be nil.

func (*Context) Untrust added in v1.1.0

func (ctx *Context) Untrust() (ok bool)

Untrust deletes given ip from trustedIP list, that enables protection of Protect()'ed endpoints for given ip too. Opposite of Context.Whitelist().

See also App.Protect(), App.Whitelist(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), App.Untrust(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Whitelist(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*Context) Whitelist added in v1.1.0

func (ctx *Context) Whitelist() (ok bool)

Whitelist adds given ip to trustedIP list of the Gramework Protection. To remove IP from whitelist, call App.Untrust()

See also App.Protect(), App.Untrust(), App.Blacklist(), App.Suspect(), App.MaxHackAttempts(), App.Whitelist(), Context.Untrust(), Context.IsWhitelisted(), Context.IsBlacklisted(), Context.IsSuspect(), Context.Blacklist(), Context.Suspect(), Context.HackAttemptDetected(), Context.SuspectsHackAttempts()

func (*Context) Write added in v1.7.0

func (ctx *Context) Write(p []byte) (int, error)

func (*Context) Writef

func (ctx *Context) Writef(format string, a ...interface{}) (int, error)

Writef is a fmt.Fprintf(context, format, a...) shortcut

func (*Context) Writeln

func (ctx *Context) Writeln(a ...interface{}) (int, error)

Writeln is a fmt.Fprintln(context, format, a...) shortcut

func (*Context) XML added in v1.1.0

func (ctx *Context) XML(v interface{}) error

XML sends text/xml content type (see rfc3023, sec 3) and xml-encoded value to client

type Cookies

type Cookies struct {
	Storage map[string]string
	Mu      sync.RWMutex
}

Cookies handles a typical cookie storage

func (*Cookies) Exists

func (c *Cookies) Exists(key string) bool

Exists reports if the given key exists for current request

func (*Cookies) Get

func (c *Cookies) Get(key string) (string, bool)

Get a cookie by given key

func (*Cookies) Set

func (c *Cookies) Set(key, value string)

Set a cookie with given key to the value

type Environment added in v1.1.0

type Environment int32

Environment defines which environment gramework application runs in. It may be useful in various cases.

const (
	// DEV is the default environment
	DEV Environment = iota
	// STAGE envoronment works just like prod environment,
	// but with detailed logs
	STAGE
	// PROD environment itself
	PROD
)

func GetEnv added in v1.1.0

func GetEnv() Environment

GetEnv returns current gramework's environment

func (Environment) String added in v1.1.0

func (e Environment) String() string

type FastHTTPLoggerAdapter added in v1.1.0

type FastHTTPLoggerAdapter struct {
	fasthttp.Logger
	// contains filtered or unexported fields
}

FastHTTPLoggerAdapter Adapter for passing apex/log used as gramework Logger into fasthttp

func NewFastHTTPLoggerAdapter added in v1.1.0

func NewFastHTTPLoggerAdapter(logger *log.Interface) (fasthttplogger *FastHTTPLoggerAdapter)

NewFastHTTPLoggerAdapter create new *FastHTTPLoggerAdapter

func (*FastHTTPLoggerAdapter) Printf added in v1.1.0

func (l *FastHTTPLoggerAdapter) Printf(msg string, v ...interface{})

Printf show message only if set app.Logger.Level = apex/log.DebugLevel

type FirewallSettings

type FirewallSettings struct {
	// MaxReqPerMin is a max request per minute count
	MaxReqPerMin int64
	// BlockTimeout in seconds
	BlockTimeout int64
}

FirewallSettings represents a new firewall settings. Internal firewall representation copies this settings atomically.

type Flag

type Flag struct {
	Name        string
	Description string
	Default     string
	Value       *string
}

Flag is a flag representation

type Flags

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

Flags is a flags storage

type GQLRequest added in v1.1.0

type GQLRequest struct {
	Query         string                 `json:"query"`
	OperationName string                 `json:"operationName"`
	Variables     map[string]interface{} `json:"variables"`
}

GQLRequest is a GraphQL request structure

type HTML added in v1.2.0

type HTML string

HTML type used to determine prerendered strings as an HTML and give proper content-type

type JSON added in v1.2.3

type JSON string

JSON type used to determine prerendered strings as an JSON and give proper content-type

type RequestHandler

type RequestHandler func(*Context)

RequestHandler describes a standard request handler type

func NewGrameHandler

func NewGrameHandler(h http.Handler) RequestHandler

NewGrameHandler wraps net/http handler to fasthttp request handler, so it can be passed to fasthttp server.

While this function may be used for easy switching from net/http to fasthttp, it has the following drawbacks comparing to using manually written fasthttp request handler:

  • A lot of useful functionality provided by fasthttp is missing from net/http handler.
  • net/http -> fasthttp handler conversion has some overhead, so the returned handler will be always slower than manually written fasthttp handler.

So it is advisable using this function only for quick net/http -> fasthttp switching. Then manually convert net/http handlers to fasthttp handlers according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .

This adaptor is a fork of https://github.com/valyala/fasthttp/tree/master/fasthttpadaptor We're embedding it because we don't want additional allocation, but we need exactly gramework request handler, not fasthttp request handler. The package provides helper functions for converting net/http request handlers to fasthttp request handlers. See the original license in /3rd-Party Licenses/fasthttp

func NewGrameHandlerFunc

func NewGrameHandlerFunc(h http.HandlerFunc) RequestHandler

NewGrameHandlerFunc wraps net/http handler func to gramework request handler, so it can be passed to gramework router.

While this function may be used for easy switching from net/http to gramework, it has the following drawbacks comparing to using manually written gramework request handler:

  • A lot of useful functionality provided by fasthttp is missing from net/http handler.
  • net/http -> fasthttp handler conversion has some overhead, so the returned handler will be always slower than manually written fasthttp handler.

So it is advisable using this function only for quick net/http -> fasthttp switching. Then manually convert net/http handlers to fasthttp handlers according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .

This adaptor is a fork of https://github.com/valyala/fasthttp/tree/master/fasthttpadaptor We're embedding it because we don't want additional allocation, but we need exactly gramework request handler, not fasthttp request handler. The package provides helper functions for converting net/http request handlers to fasthttp request handlers. See the original license in /3rd-Party Licenses/fasthttp

type RequestHandlerErr

type RequestHandlerErr func(*Context) error

RequestHandlerErr describes a standard request handler with error returned type

type Router

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

Router handles internal handler conversion etc.

func (*Router) Allowed

func (r *Router) Allowed(path, reqMethod string) (allow string)

Allowed returns Allow header's value used in OPTIONS responses

func (*Router) DELETE

func (r *Router) DELETE(route string, handler interface{}) *Router

DELETE registers a handler for a DELETE request to the given route

func (*Router) Forbidden

func (r *Router) Forbidden(ctx *Context)

Forbidden serves 403 on route it registered on

func (*Router) GET

func (r *Router) GET(route string, handler interface{}) *Router

GET registers a handler for a GET request to the given route

func (*Router) HEAD

func (r *Router) HEAD(route string, handler interface{}) *Router

HEAD registers a handler for a HEAD request to the given route

func (*Router) HTTP

func (r *Router) HTTP() *Router

HTTP router returns a router instance that work only on HTTP requests

func (*Router) HTTPS

func (r *Router) HTTPS() *Router

HTTPS router returns a router instance that work only on HTTPS requests

func (*Router) Handle

func (r *Router) Handle(method, route string, handler interface{}) *Router

Handle registers a new request handle with the given path and method. For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used. This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) HandleMethodNotAllowed

func (r *Router) HandleMethodNotAllowed(newValue bool) (oldValue bool)

HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router

func (*Router) HandleOPTIONS

func (r *Router) HandleOPTIONS(newValue bool) (oldValue bool)

HandleOPTIONS changes HandleOPTIONS mode in the router

func (*Router) Handler

func (r *Router) Handler() func(*Context)

Handler makes the router implement the fasthttp.ListenAndServe interface.

func (*Router) JSON

func (r *Router) JSON(route string, handler interface{}) *Router

JSON register internal handler that sets json content type and serves given handler with GET method

func (*Router) Lookup

func (r *Router) Lookup(method, path string, ctx *Context) (RequestHandler, bool)

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) MethodNotAllowed

func (r *Router) MethodNotAllowed(c func(ctx *Context))

MethodNotAllowed sets MethodNotAllowed handler

func (*Router) NotFound

func (r *Router) NotFound(notFoundHandler func(*Context))

NotFound set a handler which is called when no matching route is found

func (*Router) OPTIONS

func (r *Router) OPTIONS(route string, handler interface{}) *Router

OPTIONS registers a handler for a OPTIONS request to the given route

func (*Router) PATCH

func (r *Router) PATCH(route string, handler interface{}) *Router

PATCH registers a handler for a PATCH request to the given route

func (*Router) POST

func (r *Router) POST(route string, handler interface{}) *Router

POST registers a handler for a POST request to the given route

func (*Router) PUT

func (r *Router) PUT(route string, handler interface{}) *Router

PUT registers a handler for a PUT request to the given route

func (*Router) PanicHandler

func (r *Router) PanicHandler(panicHandler func(*Context, interface{}))

PanicHandler set a handler for unhandled panics

func (*Router) Redir

func (r *Router) Redir(route, url string)

Redir sends 301 redirect to the given url

it's equivalent to

ctx.Redirect(url, 301)

func (*Router) SPAIndex

func (r *Router) SPAIndex(pathOrHandler interface{}) *Router

SPAIndex serves an index file or handler on any unregistered route

func (*Router) ServeFile

func (r *Router) ServeFile(route, file string) *Router

ServeFile serves a file on a given route

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, rootPath string)

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler.

router.ServeFiles("/src/*filepath", "/var/www")

func (*Router) Sub

func (r *Router) Sub(path string) *SubRouter

Sub let you quickly register subroutes with given prefix like app.Sub("v1").GET("route", "hi"), that give you /v1/route registered

type Settings

type Settings struct {
	Firewall FirewallSettings
}

Settings for an App instance

type SubRouter

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

SubRouter handles subs registration like app.Sub("v1").GET("someRoute", "hi")

func (*SubRouter) DELETE

func (r *SubRouter) DELETE(route string, handler interface{}) *SubRouter

DELETE registers a handler for a DELETE request to the given route

func (*SubRouter) Forbidden

func (r *SubRouter) Forbidden(ctx *Context)

Forbidden is a shortcut for ctx.Forbidden

func (*SubRouter) GET

func (r *SubRouter) GET(route string, handler interface{}) *SubRouter

GET registers a handler for a GET request to the given route

func (*SubRouter) HEAD

func (r *SubRouter) HEAD(route string, handler interface{}) *SubRouter

HEAD registers a handler for a HEAD request to the given route

func (*SubRouter) HTTP

func (r *SubRouter) HTTP() *SubRouter

HTTP returns SubRouter for http requests with given r.prefix

func (*SubRouter) HTTPS

func (r *SubRouter) HTTPS() *SubRouter

HTTPS returns SubRouter for https requests with given r.prefix

func (*SubRouter) Handle added in v1.3.2

func (r *SubRouter) Handle(method, route string, handler interface{}) *SubRouter

Handle registers a new request handle with the given path and method. For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used. This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*SubRouter) JSON

func (r *SubRouter) JSON(route string, handler interface{}) *SubRouter

JSON register internal handler that sets json content type and serves given handler with GET method

func (*SubRouter) OPTIONS

func (r *SubRouter) OPTIONS(route string, handler interface{}) *SubRouter

OPTIONS registers a handler for a OPTIONS request to the given route

func (*SubRouter) PATCH

func (r *SubRouter) PATCH(route string, handler interface{}) *SubRouter

PATCH registers a handler for a PATCH request to the given route

func (*SubRouter) POST

func (r *SubRouter) POST(route string, handler interface{}) *SubRouter

POST registers a handler for a POST request to the given route

func (*SubRouter) PUT

func (r *SubRouter) PUT(route string, handler interface{}) *SubRouter

PUT registers a handler for a PUT request to the given route

func (*SubRouter) Redir

func (r *SubRouter) Redir(route, url string)

Redir sends 301 redirect to the given url

it's equivalent to

ctx.Redirect(url, 301)

func (*SubRouter) ServeFile

func (r *SubRouter) ServeFile(route, file string) *SubRouter

ServeFile serves a file on a given route

func (*SubRouter) Sub

func (r *SubRouter) Sub(path string) *SubRouter

Sub let you quickly register subroutes with given prefix like app.Sub("v1").Sub("users").GET("view/:id", "hi").DELETE("delete/:id", "hi"), that give you /v1/users/view/:id and /v1/users/delete/:id registered

func (*SubRouter) ToTLSHandler

func (r *SubRouter) ToTLSHandler() func(*Context)

ToTLSHandler returns handler that redirects user to HTTP scheme

Directories

Path Synopsis
behind
akamai
Package akamai provides a gramework.Behind implementation developed for Gramework.
Package akamai provides a gramework.Behind implementation developed for Gramework.
akamai/internal/portWhitelist
Package portWhitelist provides a parser for the Akamai's CIDR blocks Port field syntax.
Package portWhitelist provides a parser for the Akamai's CIDR blocks Port field syntax.
Package grypto provides helpers for dealing with cryptography.
Package grypto provides helpers for dealing with cryptography.
Deprecated: will be moved into another package.
Deprecated: will be moved into another package.
internal
mw
xhostname
Package xhostname middleware provides `X-Hostname` header in each request and useful when using scalable container platform to see which host sent you current response.
Package xhostname middleware provides `X-Hostname` header in each request and useful when using scalable container platform to see which host sent you current response.
test
x

Jump to

Keyboard shortcuts

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