Documentation ¶
Index ¶
- Constants
- Variables
- func BytesToString(b []byte) string
- func CleanPath(p string) string
- func DefaultPanicHandler(ctx *Context, panicReason interface{})
- func DisableFlags()
- func Errorf(msg string, v ...interface{})
- func Nanotime() int64
- func OptMaxRequestBodySize(new int) func(*App)
- func OptUseServer(s *fasthttp.Server) func(*App)
- func SetEnv(e Environment)
- func StringToBytes(s string) []byte
- func TicksPerSecond() int64
- func UnJSONBytes(b []byte, v ...interface{}) (interface{}, error)
- type App
- func (app *App) AddFlag(f Flag)
- func (app *App) Blacklist(ip net.IP) (ok bool)
- func (app *App) CORSMiddleware(domains ...string) func(*Context)
- func (app *App) DELETE(route string, handler interface{}) *App
- func (app *App) Domain(domain string) *Router
- func (app *App) Forbidden(ctx *Context)
- func (app *App) GET(route string, handler interface{}) *App
- func (app *App) GetStringFlag(name string) (string, bool)
- func (app *App) HEAD(route string, handler interface{}) *App
- func (app *App) HTTP() *Router
- func (app *App) HTTPS() *Router
- func (app *App) Handle(method, route string, handler interface{}) *App
- func (app *App) HandleMethodNotAllowed(newValue bool) (oldValue bool)
- func (app *App) HandleOPTIONS(newValue bool) (oldValue bool)
- func (app *App) Health()
- func (app *App) HealthHandler(ctx *Context)
- func (app *App) JSON(route string, handler interface{}) *App
- func (app *App) ListenAndServe(addr ...string) error
- func (app *App) ListenAndServeAll(httpAddr ...string)
- func (app *App) ListenAndServeAllDev(httpAddr ...string)
- func (app *App) ListenAndServeAutoTLS(addr string, cachePath ...string) error
- func (app *App) ListenAndServeAutoTLSDev(addr string, cachePath ...string) error
- func (app *App) MaxHackAttempts(attempts int32) (oldValue int32)
- func (app *App) MethodNotAllowed(c func(ctx *Context)) *App
- func (app *App) NotFound(notFoundHandler func(*Context)) *App
- func (app *App) OPTIONS(route string, handler interface{}) *App
- func (app *App) PATCH(route string, handler interface{}) *App
- func (app *App) POST(route string, handler interface{}) *App
- func (app *App) PUT(route string, handler interface{}) *App
- func (app *App) PanicHandler(panicHandler func(*Context, interface{})) *App
- func (app *App) Protect(endpointPrefix string)
- func (app *App) Redir(url string) func(*Context)
- func (app *App) RegFlags()
- func (app *App) SPAIndex(pathOrHandler interface{}) *Router
- func (app *App) Serve(ln net.Listener) error
- func (app *App) ServeDir(path string) func(*Context)
- func (app *App) ServeDirCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, ...) func(*Context)
- func (app *App) ServeDirNoCache(path string) func(*Context)
- func (app *App) ServeDirNoCacheCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, ...) func(*Context)
- func (app *App) ServeFile(route, file string) *Router
- func (app *App) ServeInfrastructure(i *infrastructure.Infrastructure)
- func (app *App) SetCookieDomain(domain string)
- func (app *App) SetCookieExpire(d time.Duration)
- func (app *App) SetCookiePath(path string)
- func (app *App) SetName(name string)
- func (app *App) Shutdown() (err error)
- func (app *App) Sub(path string) *SubRouter
- func (app *App) Suspect(ip net.IP) (ok bool)
- func (app *App) ToTLSHandler() func(*Context)
- func (app *App) Untrust(ip net.IP) (ok bool)
- func (app *App) Use(middleware interface{}) error
- func (app *App) UseAfterRequest(middleware interface{}) error
- func (app *App) UsePre(middleware interface{}) error
- func (app *App) Whitelist(ip net.IP) (ok bool)
- type Auth
- type Context
- func (ctx *Context) Auth() *Auth
- func (ctx *Context) BadRequest(err ...error)
- func (ctx *Context) Blacklist() (ok bool)
- func (ctx *Context) CORS(domains ...string) *Context
- func (ctx *Context) CSV(v interface{}) error
- func (ctx *Context) ContentType() string
- func (ctx *Context) DecodeGQL() (r *GQLRequest, err error)
- func (ctx *Context) Encode(v interface{}) (sentType string, err error)
- func (ctx *Context) Err500(message ...interface{}) *Context
- func (ctx *Context) Forbidden()
- func (ctx *Context) GETKeys() []string
- func (ctx *Context) GETKeysBytes() [][]byte
- func (ctx *Context) GETParam(argName string) []string
- func (ctx *Context) GETParams() map[string][]string
- func (ctx *Context) GetCookieDomain() (domain string, wasConfigured bool)
- func (ctx *Context) HTML() *Context
- func (ctx *Context) HackAttemptDetected()
- func (ctx *Context) IsBlacklisted() (isBlacklisted bool)
- func (ctx *Context) IsSuspect() (isSuspect bool)
- func (ctx *Context) IsWhitelisted() (isWhitelisted bool)
- func (ctx *Context) JSON(v interface{}) error
- func (ctx *Context) JSONError(v interface{}) error
- func (ctx *Context) LogHeaders()
- func (ctx *Context) MWKill()
- func (ctx *Context) Proxy(url string) error
- func (ctx *Context) RequestID() string
- func (ctx *Context) RouteArg(argName string) string
- func (ctx *Context) RouteArgErr(argName string) (string, error)
- func (ctx *Context) SubPrefixes() []string
- func (ctx *Context) Suspect() (ok bool)
- func (ctx *Context) SuspectsHackAttempts() (attempts int32)
- func (ctx *Context) ToCSV(v interface{}) (b []byte, err error)
- func (ctx *Context) ToContext(parentCtx ...context.Context) context.Context
- func (ctx *Context) ToJSON(v interface{}) ([]byte, error)
- func (ctx *Context) ToTLS()
- func (ctx *Context) ToXML(v interface{}) ([]byte, error)
- func (ctx *Context) UnJSON(v interface{}) error
- func (ctx *Context) UnJSONBytes(b []byte, v ...interface{}) (interface{}, error)
- func (ctx *Context) Untrust() (ok bool)
- func (ctx *Context) Whitelist() (ok bool)
- func (ctx *Context) Writef(format string, a ...interface{})
- func (ctx *Context) Writeln(a ...interface{})
- func (ctx *Context) XML(v interface{}) error
- type Cookies
- type Environment
- type FastHTTPLoggerAdapter
- type FirewallSettings
- type Flag
- type Flags
- type GQLRequest
- type HTML
- type JSON
- type RequestHandler
- type RequestHandlerErr
- type Router
- func (r *Router) Allowed(path, reqMethod string) (allow string)
- func (r *Router) DELETE(route string, handler interface{}) *Router
- func (r *Router) Forbidden(ctx *Context)
- func (r *Router) GET(route string, handler interface{}) *Router
- func (r *Router) HEAD(route string, handler interface{}) *Router
- func (r *Router) HTTP() *Router
- func (r *Router) HTTPS() *Router
- func (r *Router) Handle(method, route string, handler interface{}) *Router
- func (r *Router) HandleMethodNotAllowed(newValue bool) (oldValue bool)
- func (r *Router) HandleOPTIONS(newValue bool) (oldValue bool)
- func (r *Router) Handler() func(*Context)
- func (r *Router) JSON(route string, handler interface{}) *Router
- func (r *Router) Lookup(method, path string, ctx *Context) (RequestHandler, bool)
- func (r *Router) MethodNotAllowed(c func(ctx *Context))
- func (r *Router) NotFound(notFoundHandler func(*Context))
- func (r *Router) OPTIONS(route string, handler interface{}) *Router
- func (r *Router) PATCH(route string, handler interface{}) *Router
- func (r *Router) POST(route string, handler interface{}) *Router
- func (r *Router) PUT(route string, handler interface{}) *Router
- func (r *Router) PanicHandler(panicHandler func(*Context, interface{}))
- func (r *Router) Redir(route, url string)
- func (r *Router) SPAIndex(pathOrHandler interface{}) *Router
- func (r *Router) ServeFile(route, file string) *Router
- func (r *Router) ServeFiles(path string, rootPath string)
- func (r *Router) Sub(path string) *SubRouter
- type Settings
- type SubRouter
- func (r *SubRouter) DELETE(route string, handler interface{}) *SubRouter
- func (r *SubRouter) Forbidden(ctx *Context)
- func (r *SubRouter) GET(route string, handler interface{}) *SubRouter
- func (r *SubRouter) HEAD(route string, handler interface{}) *SubRouter
- func (r *SubRouter) HTTP() *SubRouter
- func (r *SubRouter) HTTPS() *SubRouter
- func (r *SubRouter) JSON(route string, handler interface{}) *SubRouter
- func (r *SubRouter) OPTIONS(route string, handler interface{}) *SubRouter
- func (r *SubRouter) PATCH(route string, handler interface{}) *SubRouter
- func (r *SubRouter) POST(route string, handler interface{}) *SubRouter
- func (r *SubRouter) PUT(route string, handler interface{}) *SubRouter
- func (r *SubRouter) Redir(route, url string)
- func (r *SubRouter) ServeFile(route, file string) *SubRouter
- func (r *SubRouter) Sub(path string) *SubRouter
- func (r *SubRouter) ToTLSHandler() func(*Context)
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 (
// 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
const Version = "1.2.3"
Version gives you the gramework version you use now
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") )
Logger handles default logger
Functions ¶
func BytesToString ¶ added in v1.1.0
BytesToString effectively converts bytes to string nolint: gas
func CleanPath ¶
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:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- 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 OptMaxRequestBodySize ¶ added in v1.1.0
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 OptUseServer ¶ added in v1.1.0
OptUseServer sets fasthttp.Server instance to use
func StringToBytes ¶ added in v1.1.0
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 ¶
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 EnableFirewall bool HandleUnknownDomains bool NoDefaultPanicHandler bool PanicHandlerNoPoweredBy bool PanicHandlerCustomLayout string // contains filtered or unexported fields }
App represents a gramework app
func (*App) AddFlag ¶
AddFlag adds a Flag to flag queue that will be parsed if flags wasn't parsed yet
func (*App) Blacklist ¶ added in v1.1.0
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 ¶
CORSMiddleware provides gramework handler with ctx.CORS() call
func (*App) GetStringFlag ¶ added in v1.1.0
GetStringFlag return command line app flag value by name and false if not exists
func (*App) Handle ¶
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 ¶
HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router
func (*App) HandleOPTIONS ¶
HandleOPTIONS changes HandleOPTIONS mode in the router
func (*App) HealthHandler ¶
HealthHandler serves info about memory usage
func (*App) JSON ¶
JSON register internal handler that sets json content type and serves given handler with GET method
func (*App) ListenAndServe ¶
ListenAndServe HTTP on given addr. runs flag.Parse() if !flag.Parsed() to support --bind flag.
func (*App) ListenAndServeAll ¶
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 ¶
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().
func (*App) ListenAndServeAutoTLS ¶
ListenAndServeAutoTLS serves TLS requests
func (*App) ListenAndServeAutoTLSDev ¶
ListenAndServeAutoTLSDev serves non-production grade TLS requests. Supports localhost.localdomain.
func (*App) MaxHackAttempts ¶ added in v1.1.0
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 ¶
MethodNotAllowed sets MethodNotAllowed handler
func (*App) PanicHandler ¶
PanicHandler set a handler for unhandled panics
func (*App) Protect ¶ added in v1.1.0
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 ¶
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) 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 ¶
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) ServeInfrastructure ¶
func (app *App) ServeInfrastructure(i *infrastructure.Infrastructure)
ServeInfrastructure serves Infrastructure info It's an integration of our module
func (*App) SetCookieDomain ¶ added in v1.1.0
SetCookieDomain allows you to implement SSO and other useful features without additional pain
func (*App) SetCookieExpire ¶ added in v1.2.1
SetCookieExpire allows you set cookie expire time
func (*App) SetCookiePath ¶ added in v1.2.2
SetCookiePath allows you set cookie path
func (*App) Sub ¶
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
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 ¶
ToTLSHandler returns handler that redirects user to HTTPS scheme
func (*App) Untrust ¶ added in v1.1.0
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) UseAfterRequest ¶
UseAfterRequest the middleware after request processing
func (*App) UsePre ¶
UsePre registers middleware before any other middleware. Use only for metrics or access control!
func (*App) Whitelist ¶ added in v1.1.0
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
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
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
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
BadRequest sends HTTP/1.1 400 Bad Request
func (*Context) Blacklist ¶ added in v1.1.0
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) CSV ¶ added in v1.1.0
CSV sends text/csv content type (see rfc4180, sec 3) and csv-encoded value to client
func (*Context) ContentType ¶ added in v1.1.0
ContentType returns Content-Type header for current request
func (*Context) DecodeGQL ¶ added in v1.1.0
func (ctx *Context) DecodeGQL() (r *GQLRequest, err error)
DecodeGQL parses GraphQL request and returns data from it
func (*Context) Encode ¶ added in v1.1.0
Encode automatically determies accepted formats and choose preferred one
func (*Context) GETKeysBytes ¶
GETKeysBytes returns GET parameters keys as []byte
func (*Context) GetCookieDomain ¶ added in v1.1.0
GetCookieDomain returns previously configured cookie domain and if cookie domain was configured at all
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
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
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
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) JSONError ¶
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) RequestID ¶ added in v1.1.0
RequestID return request ID for current context's request
func (*Context) RouteArgErr ¶
RouteArgErr returns an argument value as a string or empty string and ErrArgNotFound if argument was not found
func (*Context) SubPrefixes ¶ added in v1.1.0
SubPrefixes returns list of router's prefixes that was created using .Sub() feature
func (*Context) Suspect ¶ added in v1.1.0
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
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) ToContext ¶ added in v1.1.0
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) UnJSONBytes ¶
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
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
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()
type Cookies ¶
Cookies handles a typical cookie storage
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
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 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 ¶
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) Handle ¶
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 ¶
HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router
func (*Router) HandleOPTIONS ¶
HandleOPTIONS changes HandleOPTIONS mode in the router
func (*Router) JSON ¶
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 ¶
MethodNotAllowed sets MethodNotAllowed handler
func (*Router) PanicHandler ¶
PanicHandler set a handler for unhandled panics
func (*Router) Redir ¶
Redir sends 301 redirect to the given url
it's equivalent to
ctx.Redirect(url, 301)
func (*Router) ServeFiles ¶
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")
type SubRouter ¶
type SubRouter struct {
// contains filtered or unexported fields
}
SubRouter handles subs registration like app.Sub("v1").GET("someRoute", "hi")
func (*SubRouter) JSON ¶
JSON register internal handler that sets json content type and serves given handler with GET method
func (*SubRouter) Redir ¶
Redir sends 301 redirect to the given url
it's equivalent to
ctx.Redirect(url, 301)
func (*SubRouter) Sub ¶
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 ¶
ToTLSHandler returns handler that redirects user to HTTP scheme
Source 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
- const.go
- context.go
- context_Auth.go
- context_logHeaders.go
- context_proxy.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
- types.go
- version.go
Directories ¶
Path | Synopsis |
---|---|
Package grypto provides helpers for dealing with cryptography
|
Package grypto provides helpers for dealing with cryptography |
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. |
x
|
|