gramework: github.com/gramework/gramework Index | Files | Directories

package gramework

import "github.com/gramework/gramework"

Index

Package Files

adaptor.go app.go app_copyServer.go app_handler.go app_healthcheck.go app_listenAndServe.go app_listenAndServeAll.go app_listenAndServeAutoTLS.go app_protection.go app_router.go app_serve.go app_shutdown.go behind.go const.go context.go context_Auth.go context_getters.go context_gql.go context_logHeaders.go context_proxy.go context_writers.go conv.go cookie.go errors.go fasthttprouter_cache.go fasthttprouter_path.go fasthttprouter_router.go fasthttprouter_tree.go firewall.go handlePanic.go infrastructure.go init.go log.go middleware.go nanotime.go new.go opts.go regFlags.go router.go router_default.go router_determineHandler.go router_domain.go router_internals.go sendfile.go subroute.go tickspersecond.go tls.go tolower_go112.go types.go version.go

Constants

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"
)
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"
)
const (
    Version        = "1.7.0-rc3"
    DefaultAppName = "gramework/" + Version
)

Version gives you the gramework version you use now

const (

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

Slash constant used to minimize string allocations

Variables

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")
)
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('/')
)
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")
)
var Logger = &log.Logger{
    Level:   log.InfoLevel,
    Handler: cli.New(os.Stdout),
}

Logger handles default logger

func BytesToString Uses

func BytesToString(b []byte) string

BytesToString effectively converts bytes to string nolint: gas

func CleanPath Uses

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 Uses

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

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

func DisableFlags Uses

func DisableFlags()

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

func Errorf Uses

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

Errorf logs an error using default logger

func Nanotime Uses

func Nanotime() int64

Nanotime is monotonic time provider.

func OptAppName Uses

func OptAppName(n string) func(*App)

OptAppName sets app.name and app.serverBase.Name

func OptKeepHijackedConns Uses

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 Uses

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 Uses

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

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

func OptUseServer Uses

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

OptUseServer sets fasthttp.Server instance to use

func SetEnv Uses

func SetEnv(e Environment)

SetEnv sets gramework's environment

func StringToBytes Uses

func StringToBytes(s string) []byte

StringToBytes effectively converts string to bytes nolint: gas

func TicksPerSecond Uses

func TicksPerSecond() int64

TicksPerSecond reports cpu ticks per second counter

func UnJSONBytes Uses

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.

type App Uses

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 Uses

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

New App

func (*App) AddFlag Uses

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 Uses

func (app *App) Behind(u Behind)

func (*App) Blacklist Uses

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 Uses

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

CORSMiddleware provides gramework handler with ctx.CORS() call

func (*App) DELETE Uses

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

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

func (*App) Domain Uses

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

Domain returns a domain router

func (*App) Forbidden Uses

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

Forbidden send 403 Forbidden error

func (*App) GET Uses

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

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

func (*App) GetStringFlag Uses

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 Uses

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

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

func (*App) HTTP Uses

func (app *App) HTTP() *Router

HTTP returns HTTP-only router

func (*App) HTTPS Uses

func (app *App) HTTPS() *Router

HTTPS returns HTTPS-only router

func (*App) Handle Uses

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 Uses

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

HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router

func (*App) HandleOPTIONS Uses

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

HandleOPTIONS changes HandleOPTIONS mode in the router

func (*App) Health Uses

func (app *App) Health()

Health registers HealthHandler on /internal/health

func (*App) HealthHandler Uses

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

HealthHandler serves info about memory usage

func (*App) JSON Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

ListenAndServeAutoTLS serves TLS requests

func (*App) ListenAndServeAutoTLSDev Uses

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 Uses

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 Uses

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

MethodNotAllowed sets MethodNotAllowed handler

func (*App) NotFound Uses

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

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

func (*App) OPTIONS Uses

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

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

func (*App) PATCH Uses

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

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

func (*App) POST Uses

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

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

func (*App) PUT Uses

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

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

func (*App) PanicHandler Uses

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

PanicHandler set a handler for unhandled panics

func (*App) Protect Uses

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 Uses

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 Uses

func (app *App) RegFlags()

RegFlags registers current flag queue in flag parser

func (*App) SPAIndex Uses

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

SPAIndex serves an index file or handler on any unregistered route

func (*App) Serve Uses

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

Serve app on given listener

func (*App) ServeDir Uses

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

ServeDir from a given path

func (*App) ServeDirCustom Uses

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 Uses

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

ServeDirNoCache gives you ability to serve a dir without caching

func (*App) ServeDirNoCacheCustom Uses

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 Uses

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

ServeFile serves a file on a given route

func (*App) ServeInfrastructure Uses

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 Uses

func (app *App) SetCookieDomain(domain string)

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

func (*App) SetCookieExpire Uses

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

SetCookieExpire allows you set cookie expire time

func (*App) SetCookiePath Uses

func (app *App) SetCookiePath(path string)

SetCookiePath allows you set cookie path

func (*App) SetName Uses

func (app *App) SetName(name string)

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

func (*App) SetSanitizerPolicy Uses

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 Uses

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

Shutdown gracefully shuts down application servers

func (*App) Sub Uses

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 Uses

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 Uses

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

ToTLSHandler returns handler that redirects user to HTTPS scheme

func (*App) Untrust Uses

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 Uses

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

Use the middleware before request processing

func (*App) UseAfterRequest Uses

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

UseAfterRequest the middleware after request processing

func (*App) UsePre Uses

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

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

func (*App) Whitelist Uses

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 Uses

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

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

func (*Auth) GetLogin Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

BadRequest sends HTTP/1.1 400 Bad Request

func (*Context) Blacklist Uses

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 Uses

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

CORS enables CORS in the current context

func (*Context) CSV Uses

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 Uses

func (ctx *Context) ContentType() string

ContentType returns Content-Type header for current request

func (*Context) DecodeGQL Uses

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

DecodeGQL parses GraphQL request and returns data from it

func (*Context) Encode Uses

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

Encode automatically determines accepted formats and choose preferred one

func (*Context) Err500 Uses

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

Err500 sets Internal Server Error status

func (*Context) Forbidden Uses

func (ctx *Context) Forbidden()

Forbidden send 403 Forbidden error

func (*Context) GETKeys Uses

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

GETKeys returns GET parameters keys (query args)

func (*Context) GETKeysBytes Uses

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

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

func (*Context) GETParam Uses

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

GETParam returns GET parameter (query arg) by name

func (*Context) GETParams Uses

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

GETParams returns GET parameters (query args)

func (*Context) GetCookieDomain Uses

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 Uses

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

HTML sets HTML content type

func (*Context) HackAttemptDetected Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

JSON serializes and writes a json-formatted response to user

func (*Context) JSONError Uses

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 Uses

func (ctx *Context) LogHeaders()

LogHeaders logs all request headers for debug

func (*Context) MWKill Uses

func (ctx *Context) MWKill()

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

func (*Context) Proxy Uses

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

Proxy request to given url

func (*Context) RemoteAddr Uses

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

func (*Context) RemoteIP Uses

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

func (*Context) RequestID Uses

func (ctx *Context) RequestID() string

RequestID return request ID for current context's request

func (*Context) RouteArg Uses

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

RouteArg returns an argument value as a string or empty string

func (*Context) RouteArgErr Uses

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 Uses

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 Uses

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 Uses

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

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

func (*Context) Suspect Uses

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 Uses

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 Uses

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

ToCSV encodes csv-encoded value to client

func (*Context) ToContext Uses

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 Uses

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

ToJSON serializes v and returns the result

func (*Context) ToTLS Uses

func (ctx *Context) ToTLS()

ToTLS redirects user to HTTPS scheme

func (*Context) ToXML Uses

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

ToXML encodes xml-encoded value to client

func (*Context) UnJSON Uses

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

UnJSON deserializes JSON request body to given variable pointer

func (*Context) UnJSONBytes Uses

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 Uses

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 Uses

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 Uses

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

func (*Context) Writef Uses

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

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

func (*Context) Writeln Uses

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

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

func (*Context) XML Uses

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 Uses

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

Cookies handles a typical cookie storage

func (*Cookies) Exists Uses

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

Exists reports if the given key exists for current request

func (*Cookies) Get Uses

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

Get a cookie by given key

func (*Cookies) Set Uses

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

Set a cookie with given key to the value

type Environment Uses

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 Uses

func GetEnv() Environment

GetEnv returns current gramework's environment

func (Environment) String Uses

func (e Environment) String() string

type FastHTTPLoggerAdapter Uses

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

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

func NewFastHTTPLoggerAdapter Uses

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

NewFastHTTPLoggerAdapter create new *FastHTTPLoggerAdapter

func (*FastHTTPLoggerAdapter) Printf Uses

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

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

type FirewallSettings Uses

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 Uses

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

Flag is a flag representation

type Flags Uses

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

Flags is a flags storage

type GQLRequest Uses

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 Uses

type HTML string

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

type JSON Uses

type JSON string

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

type RequestHandler Uses

type RequestHandler func(*Context)

RequestHandler describes a standard request handler type

func NewGrameHandler Uses

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 Uses

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 Uses

type RequestHandlerErr func(*Context) error

RequestHandlerErr describes a standard request handler with error returned type

type Router Uses

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

Router handles internal handler conversion etc.

func (*Router) Allowed Uses

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

Allowed returns Allow header's value used in OPTIONS responses

func (*Router) DELETE Uses

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

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

func (*Router) Forbidden Uses

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

Forbidden serves 403 on route it registered on

func (*Router) GET Uses

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

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

func (*Router) HEAD Uses

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

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

func (*Router) HTTP Uses

func (r *Router) HTTP() *Router

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

func (*Router) HTTPS Uses

func (r *Router) HTTPS() *Router

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

func (*Router) Handle Uses

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 Uses

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

HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router

func (*Router) HandleOPTIONS Uses

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

HandleOPTIONS changes HandleOPTIONS mode in the router

func (*Router) Handler Uses

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

Handler makes the router implement the fasthttp.ListenAndServe interface.

func (*Router) JSON Uses

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 Uses

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 Uses

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

MethodNotAllowed sets MethodNotAllowed handler

func (*Router) NotFound Uses

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

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

func (*Router) OPTIONS Uses

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

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

func (*Router) PATCH Uses

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

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

func (*Router) POST Uses

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

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

func (*Router) PUT Uses

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

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

func (*Router) PanicHandler Uses

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

PanicHandler set a handler for unhandled panics

func (*Router) Redir Uses

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 Uses

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

SPAIndex serves an index file or handler on any unregistered route

func (*Router) ServeFile Uses

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

ServeFile serves a file on a given route

func (*Router) ServeFiles Uses

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 Uses

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 Uses

type Settings struct {
    Firewall FirewallSettings
}

Settings for an App instance

type SubRouter Uses

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

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

func (*SubRouter) DELETE Uses

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

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

func (*SubRouter) Forbidden Uses

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

Forbidden is a shortcut for ctx.Forbidden

func (*SubRouter) GET Uses

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

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

func (*SubRouter) HEAD Uses

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

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

func (*SubRouter) HTTP Uses

func (r *SubRouter) HTTP() *SubRouter

HTTP returns SubRouter for http requests with given r.prefix

func (*SubRouter) HTTPS Uses

func (r *SubRouter) HTTPS() *SubRouter

HTTPS returns SubRouter for https requests with given r.prefix

func (*SubRouter) Handle Uses

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 Uses

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 Uses

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

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

func (*SubRouter) PATCH Uses

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

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

func (*SubRouter) POST Uses

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

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

func (*SubRouter) PUT Uses

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

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

func (*SubRouter) Redir Uses

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 Uses

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

ServeFile serves a file on a given route

func (*SubRouter) Sub Uses

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 Uses

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

ToTLSHandler returns handler that redirects user to HTTP scheme

Directories

PathSynopsis
gqlhandler
graphiql
gryptoPackage grypto provides helpers for dealing with cryptography.
grypto/internal/mcf
grypto/providers/bcrypt
grypto/providers/scrypt
grypto/salt
healthchecks
infrastructureDeprecated: will be moved into another package.
internal/gfmt
metrics
pprof
x/client
x/sqlgen
x/testutils

Package gramework imports 43 packages (graph) and is imported by 16 packages. Updated 2019-04-02. Refresh now. Tools for package owners.