aahframe.work: aahframe.work Index | Files | Directories

package aah

import "aahframe.work"

Package aah is A secure, flexible, rapid Go web framework.

Visit: https://aahframework.org to know more.

Index

Package Files

aah.go bind.go commands.go context.go error.go event.go http_engine.go log.go middleware.go reply.go router.go security.go server.go static.go version.go view.go

Constants

const (
    // EventOnInit is published once the aah.AppConfig() is loaded. At this stage,
    // only aah.conf config is initialized. App Variables, Routes, i18n, Security,
    // View Engine, Logs and so on will be initialized after this event.
    EventOnInit = "OnInit"

    // EventOnStart is published just before the start of aah Server.
    // The application is completely initialized at this stage. The server
    // is yet to be started.
    EventOnStart = "OnStart"

    // EventOnPreShutdown is published when application receives OS Signals
    // `SIGINT` or `SIGTERM` and before the triggering graceful shutdown. After this
    // event, aah triggers graceful shutdown with config value of
    // `server.timeout.grace_shutdown`.
    EventOnPreShutdown = "OnPreShutdown"

    // EventOnPostShutdown is published just after the successful grace shutdown
    // of aah server and then application does clean exit.
    EventOnPostShutdown = "OnPostShutdown"

    // EventOnConfigHotReload is published just after aah application internal config
    // hot-reload and re-initialize completes without an error otherwise it won't be
    // published. It happens when application receives the signal based on
    // config `runtime.config_hotreload.signal`.
    EventOnConfigHotReload = "OnConfigHotReload"

    // EventOnRequest is published on each incoming request to the aah server.
    EventOnRequest = "OnRequest"

    // EventOnPreReply is published just before writing a reply/response on the wire.
    // At this point, the response writer is clean. i.e. Headers, Cookies, Redirects,
    // Status Code and Response Body are not written. event is published when
    // before server writes the reply on the wire.
    //
    // Except when
    //
    //   1) `Reply().Done()`,
    //
    //   2) `Reply().Redirect(...)` is called.
    //
    // Refer `aah.Reply().Done()` godoc for more info.
    EventOnPreReply = "OnPreReply"

    // EventOnHeaderReply is published before writing HTTP header Status.
    // At this point, all the headers except the header Status get written on
    // the http.ResponseWriter.
    //
    // Except when
    //
    //   1) `Reply().Done()`,
    //
    //   2) `Reply().Redirect(...)` is called.
    //
    // Refer `aah.Reply().Done()` godoc for more info.
    EventOnHeaderReply = "OnHeaderReply"

    // EventOnPostReply is published right after the response gets written on the
    // wire. We can do nothing about the response, however the context has valuable
    // information such as response bytes size, response status code, etc.
    //
    // Except when
    //
    //   1) `Reply().Done()`,
    //
    //   2) `Reply().Redirect(...)` is called.
    //
    // Refer `aah.Reply().Done()` godoc for more info.
    EventOnPostReply = "OnPostReply"

    // EventOnPreAuth is published just before the Authentication and Authorization.
    EventOnPreAuth = "OnPreAuth"

    // EventOnPostAuth is published once the Authentication and Authorization
    // info gets populated into Subject.
    EventOnPostAuth = "OnPostAuth"
)
const (
    // KeyViewArgAuthcInfo key name is used to store `AuthenticationInfo` instance into `ViewArgs`.
    KeyViewArgAuthcInfo = "_aahAuthcInfo"

    // KeyViewArgSubject key name is used to store `Subject` instance into `ViewArgs`.
    KeyViewArgSubject = "_aahSubject"

    // KeyOAuth2Token key name is used to store OAuth2 Access Token into `aah.Context`.
    KeyOAuth2Token = "_aahOAuth2Token"
)
const (
    // KeyViewArgRequest key name is used to store HTTP Request instance
    // into `ViewArgs`.
    KeyViewArgRequest = "_aahRequest"
)
const Version = "0.13.0-edge"

Version no. of aah framework

Variables

var (
    ErrPanicRecovery              = errors.New("aah: panic recovery")
    ErrDomainNotFound             = errors.New("aah: domain not found")
    ErrRouteNotFound              = errors.New("aah: route not found")
    ErrStaticFileNotFound         = errors.New("aah: static file not found")
    ErrControllerOrActionNotFound = errors.New("aah: controller or action not found")
    ErrInvalidRequestParameter    = errors.New("aah: invalid request parameter")
    ErrContentTypeNotAccepted     = errors.New("aah: content type not accepted")
    ErrContentTypeNotOffered      = errors.New("aah: content type not offered")
    ErrHTTPMethodNotAllowed       = errors.New("aah: http method not allowed")
    ErrNotAuthenticated           = errors.New("aah: not authenticated")
    ErrAccessDenied               = errors.New("aah: access denied")
    ErrAuthenticationFailed       = errors.New("aah: authentication failed")
    ErrAuthorizationFailed        = errors.New("aah: authorization failed")
    ErrSessionAuthenticationInfo  = errors.New("aah: session authentication info")
    ErrUnableToGetPrincipal       = errors.New("aah: unable to get principal")
    ErrGeneric                    = errors.New("aah: generic error")
    ErrValidation                 = errors.New("aah: validation error")
    ErrRenderResponse             = errors.New("aah: render response error")
    ErrWriteResponse              = errors.New("aah: write response error")
)

aah errors

func ActionMiddleware Uses

func ActionMiddleware(ctx *Context, m *Middleware)

ActionMiddleware performs

- Executes Interceptors (Before, Before<ActionName>, After, After<ActionName>,
			Panic, Panic<ActionName>, Finally, Finally<ActionName>)
- Invokes Controller Action

func AntiCSRFMiddleware Uses

func AntiCSRFMiddleware(ctx *Context, m *Middleware)

AntiCSRFMiddleware provides feature to prevent Cross-Site Request Forgery (CSRF) attacks.

func AuthcAuthzMiddleware Uses

func AuthcAuthzMiddleware(ctx *Context, m *Middleware)

AuthcAuthzMiddleware is aah Authentication and Authorization Middleware.

func BindMiddleware Uses

func BindMiddleware(ctx *Context, m *Middleware)

BindMiddleware method parses the incoming HTTP request to collects request parameters (Path, Form, Query, Multipart) stores into context. Request params are made available in View via template functions.

func CORSMiddleware Uses

func CORSMiddleware(ctx *Context, m *Middleware)

CORSMiddleware provides Cross-Origin Resource Sharing (CORS) access control feature.

func RouteMiddleware Uses

func RouteMiddleware(ctx *Context, m *Middleware)

RouteMiddleware method performs the routing logic.

type Application Uses

type Application struct {
    sync.RWMutex
    // contains filtered or unexported fields
}

Application struct represents aah application.

func App Uses

func App() *Application

App method returns the aah application instance.

func (*Application) AddCommand Uses

func (a *Application) AddCommand(cmds ...console.Command) error

AddCommand method adds the aah application CLI commands. Introduced in v0.12.0 release aah application binary fully compliant using module console and POSIX flags.

func (*Application) AddController Uses

func (a *Application) AddController(c interface{}, methods []*ainsp.Method)

AddController method adds given controller into controller registory.

func (*Application) AddLoggerHook Uses

func (a *Application) AddLoggerHook(name string, hook log.HookFunc) error

AddLoggerHook method adds given logger into aah application default logger.

func (*Application) AddPasswordAlgorithm Uses

func (a *Application) AddPasswordAlgorithm(name string, encoder acrypto.PasswordEncoder) error

AddPasswordAlgorithm method adds given password algorithm to encoders list. Implementation have to implement interface `PasswordEncoder`.

Then you can use it in the configuration `security.auth_schemes.*`.

func (*Application) AddSessionStore Uses

func (a *Application) AddSessionStore(name string, store session.Storer) error

AddSessionStore method allows you to add custom session store which implements `session.Storer` interface. Then configure `name` parameter in the configfuration as `session.store.type = "name"`.

func (*Application) AddTemplateFunc Uses

func (a *Application) AddTemplateFunc(funcs template.FuncMap)

AddTemplateFunc method adds template func map into view engine.

func (*Application) AddValueParser Uses

func (a *Application) AddValueParser(typ reflect.Type, parser valpar.Parser) error

AddValueParser method adds given custom value parser for the `reflect.Type`

func (*Application) AddViewEngine Uses

func (a *Application) AddViewEngine(name string, engine view.Enginer) error

AddViewEngine method adds the given name and view engine to view store.

func (*Application) AddWebSocket Uses

func (a *Application) AddWebSocket(w interface{}, methods []*ainsp.Method)

AddWebSocket method adds given WebSocket into WebSocket registry.

func (*Application) BaseDir Uses

func (a *Application) BaseDir() string

BaseDir method returns the application base or binary's base directory

For e.g.:
	$GOPATH/src/github.com/user/myproject
	<path/to/the/aah/myproject>
	<app/binary/path/base/directory>

func (*Application) BuildInfo Uses

func (a *Application) BuildInfo() *BuildInfo

BuildInfo method return user application version no.

func (*Application) CacheManager Uses

func (a *Application) CacheManager() *cache.Manager

CacheManager returns aah application cache manager.

func (*Application) Config Uses

func (a *Application) Config() *config.Config

Config method returns aah application configuration instance.

func (*Application) Copyrights Uses

func (a *Application) Copyrights() string

Copyrights method returns application copyrights info from configuration.

Value of `copyrights` from `aah.conf`.

func (*Application) DefaultI18nLang Uses

func (a *Application) DefaultI18nLang() string

DefaultI18nLang method returns application i18n default language if configured otherwise framework defaults to "en".

func (*Application) Desc Uses

func (a *Application) Desc() string

Desc method returns aah application friendly description from app config otherwise empty string.

Value of `desc` from `aah.conf`.

func (*Application) EnvProfile Uses

func (a *Application) EnvProfile() string

EnvProfile returns active environment profile name of aah application. For e.g.: dev, prod, etc. Default is `dev`.

Value of `env.active` from `aah.conf`.

func (*Application) EnvProfiles Uses

func (a *Application) EnvProfiles() []string

EnvProfiles method returns all available environment profile names from aah application.

func (*Application) EventStore Uses

func (a *Application) EventStore() *EventStore

EventStore method returns aah application event store.

func (*Application) HTTPAddress Uses

func (a *Application) HTTPAddress() string

HTTPAddress method returns aah application HTTP address otherwise empty string

Value of `server.address` from `aah.conf`.

func (*Application) HTTPEngine Uses

func (a *Application) HTTPEngine() *HTTPEngine

HTTPEngine method returns aah HTTP engine.

func (*Application) HTTPPort Uses

func (a *Application) HTTPPort() string

HTTPPort method returns aah application HTTP port number based on `server.port` value. Possible outcomes are user-defined port, `80`, `443` and `8080`.

func (*Application) I18n Uses

func (a *Application) I18n() i18n.I18ner

I18n method returns aah application I18n store instance.

func (*Application) ImportPath Uses

func (a *Application) ImportPath() string

ImportPath method returns the application Go import path.

func (*Application) InitForCLI Uses

func (a *Application) InitForCLI(importPath string) error

InitForCLI method is for purpose aah CLI tool. IT IS NOT FOR AAH USER. Introduced in v0.12.0 release.

func (*Application) InstanceName Uses

func (a *Application) InstanceName() string

InstanceName method returns aah application instane name from app config `instance_name` otherwise empty string.

Value of `instance_name` from `aah.conf`.

func (*Application) IsEnvProfile Uses

func (a *Application) IsEnvProfile(envProfile string) bool

IsEnvProfile method returns true if given environment profile match with active environment in aah application otherwise false.

func (*Application) IsLetsEncryptEnabled Uses

func (a *Application) IsLetsEncryptEnabled() bool

IsLetsEncryptEnabled method returns true if aah application is enabled with Let's Encrypt certs otherwise false.

func (*Application) IsPackaged Uses

func (a *Application) IsPackaged() bool

IsPackaged method returns true when application built for deployment.

func (*Application) IsSSLEnabled Uses

func (a *Application) IsSSLEnabled() bool

IsSSLEnabled method returns true if aah application is enabled with SSL otherwise false.

func (*Application) IsWebSocketEnabled Uses

func (a *Application) IsWebSocketEnabled() bool

IsWebSocketEnabled method returns to true if aah application enabled with WebSocket feature.

Value of `server.websocket.enable` from `aah.conf`.

func (*Application) Log Uses

func (a *Application) Log() log.Loggerer

Log method returns app logger instance.

func (*Application) Name Uses

func (a *Application) Name() string

Name method returns aah application name from app config `name` otherwise app name of the base directory.

func (*Application) NewChildLogger Uses

func (a *Application) NewChildLogger(fields log.Fields) log.Loggerer

NewChildLogger method create a child logger from aah application default logger.

func (*Application) OnConfigHotReload Uses

func (a *Application) OnConfigHotReload(ecb EventCallbackFunc, priority ...int)

OnConfigHotReload method is to subscribe to aah application `OnConfigHotReload` event. `OnConfigHotReload` is published just after aah application internal config hot-reload and re-initialize completes without an error otherwise it won't be published.

func (*Application) OnInit Uses

func (a *Application) OnInit(ecb EventCallbackFunc, priority ...int)

OnInit method is to subscribe to aah application `OnInit` event. `OnInit` event published right after the aah application configuration `aah.conf` initialized.

func (*Application) OnPostShutdown Uses

func (a *Application) OnPostShutdown(ecb EventCallbackFunc, priority ...int)

OnPostShutdown method is to subscribe to aah application `OnPostShutdown` event. `OnPostShutdown` event pubished right the successful grace shutdown of aah server.

func (*Application) OnPreShutdown Uses

func (a *Application) OnPreShutdown(ecb EventCallbackFunc, priority ...int)

OnPreShutdown method is to subscribe to aah application `OnPreShutdown` event. `OnPreShutdown` event pubished right before the triggering aah server graceful shutdown.

func (*Application) OnStart Uses

func (a *Application) OnStart(ecb EventCallbackFunc, priority ...int)

OnStart method is to subscribe to aah application `OnStart` event. `OnStart` event pubished right before the aah server starts listening to the request.

func (*Application) PublishEvent Uses

func (a *Application) PublishEvent(eventName string, data interface{})

PublishEvent method publishes events to subscribed callbacks asynchronously. It means each subscribed callback executed via goroutine.

func (*Application) PublishEventSync Uses

func (a *Application) PublishEventSync(eventName string, data interface{})

PublishEventSync method publishes events to subscribed callbacks synchronously.

func (*Application) RegisterI18n Uses

func (a *Application) RegisterI18n(ms i18n.I18ner)

RegisterI18n method is used to register the i18n message store into aah appplication the implements interface `i18n.I18ner`.

func (*Application) Router Uses

func (a *Application) Router() *router.Router

Router method returns aah application router instance.

func (*Application) Run Uses

func (a *Application) Run(args []string) error

Run method initializes `aah` application and runs the given command. If anything goes wrong during an initialize process, it would return an error.

func (*Application) SecurityManager Uses

func (a *Application) SecurityManager() *security.Manager

SecurityManager method returns the application security instance, which manages the Session, CORS, CSRF, Security Headers, etc.

func (*Application) ServeHTTP Uses

func (a *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP method implementation of http.Handler interface.

func (*Application) SessionManager Uses

func (a *Application) SessionManager() *session.Manager

SessionManager method returns the application session manager. By default session is stateless.

func (*Application) SetBuildInfo Uses

func (a *Application) SetBuildInfo(bi *BuildInfo)

SetBuildInfo method sets the user application build info into aah instance.

func (*Application) SetErrorHandler Uses

func (a *Application) SetErrorHandler(handlerFunc ErrorHandlerFunc)

SetErrorHandler method is used to register custom centralized application error handler. If custom handler is not then default error handler takes place.

func (*Application) SetMinifier Uses

func (a *Application) SetMinifier(fn MinifierFunc)

SetMinifier method sets the given minifier func into aah framework. Note: currently minifier is called only for HTML contentType.

func (*Application) SetPackaged Uses

func (a *Application) SetPackaged(pack bool)

SetPackaged method sets the info of binary is packaged or not.

It is used by framework during application startup. IT'S NOT FOR AAH USER(S).

func (*Application) SetTLSConfig Uses

func (a *Application) SetTLSConfig(tlsCfg *tls.Config)

SetTLSConfig method is used to set custom TLS config for aah server. Note: if `server.ssl.lets_encrypt.enable=true` then framework sets the `GetCertificate` from autocert manager.

Use `aah.OnInit` or `func init() {...}` to assign your custom TLS Config.

func (*Application) Shutdown Uses

func (a *Application) Shutdown()

Shutdown method allows aah server to shutdown gracefully with given timeout in seconds. It's invoked on OS signal `SIGINT` and `SIGTERM`.

Method performs:

- Graceful server shutdown with timeout by `server.timeout.grace_shutdown`
- Publishes `OnPostShutdown` event
- Exits program with code 0

func (*Application) Start Uses

func (a *Application) Start()

Start method starts the Go HTTP server based on aah config "server.*".

func (*Application) SubscribeEvent Uses

func (a *Application) SubscribeEvent(eventName string, ec EventCallback)

SubscribeEvent method is to subscribe to new or existing event.

func (*Application) SubscribeEventFunc Uses

func (a *Application) SubscribeEventFunc(eventName string, ecf EventCallbackFunc)

SubscribeEventFunc method is to subscribe to new or existing event by `EventCallbackFunc`.

func (*Application) Type Uses

func (a *Application) Type() string

Type method returns aah application type info e.g.: web, api, websocket.

Value of `type` from `aah.conf`.

func (*Application) UnsubscribeEvent Uses

func (a *Application) UnsubscribeEvent(eventName string, ec EventCallback)

UnsubscribeEvent method is to unsubscribe by event name and `EventCallback` from app event store.

func (*Application) UnsubscribeEventFunc Uses

func (a *Application) UnsubscribeEventFunc(eventName string, ecf EventCallbackFunc)

UnsubscribeEventFunc method is to unsubscribe by event name and `EventCallbackFunc` from app event store.

func (*Application) VFS Uses

func (a *Application) VFS() *vfs.VFS

VFS method returns aah Virtual FileSystem instance.

func (*Application) Validate Uses

func (a *Application) Validate(s interface{}) (validator.ValidationErrors, error)

Validate method is to validate struct via underneath validator.

Returns:

- For validation errors: returns `validator.ValidationErrors` and nil

- For invalid input: returns nil, error (invalid input such as nil, non-struct, etc.)

- For no validation errors: nil, nil

func (*Application) ValidateValue Uses

func (a *Application) ValidateValue(v interface{}, rules string) bool

ValidateValue method is to validate individual value on demand.

Returns -

- true: validation passed

- false: validation failed

For example:

i := 15
result := valpar.ValidateValue(i, "gt=1,lt=10")

emailAddress := "sample@sample"
result := valpar.ValidateValue(emailAddress, "email")

numbers := []int{23, 67, 87, 23, 90}
result := valpar.ValidateValue(numbers, "unique")

func (*Application) Validator Uses

func (a *Application) Validator() *validator.Validate

Validator method return the default validator of aah framework.

Refer to https://godoc.org/gopkg.in/go-playground/validator.v9 for detailed documentation.

func (*Application) ViewEngine Uses

func (a *Application) ViewEngine() view.Enginer

ViewEngine method returns aah application view Engine instance.

func (*Application) VirtualBaseDir Uses

func (a *Application) VirtualBaseDir() string

VirtualBaseDir method returns "/app". In `v0.11.0` Virtual FileSystem (VFS) introduced in aah to provide single binary build packaging and provides seamless experience of Read-Only access to application directory and its sub-tree across OS platforms via `aah.App().VFS()`.

func (*Application) WSEngine Uses

func (a *Application) WSEngine() *ws.Engine

WSEngine method returns aah WebSocket engine.

Note: It could be nil if WebSocket is not enabled.

type BuildInfo Uses

type BuildInfo struct {
    BinaryName string
    Version    string
    Timestamp  string
    AahVersion string // introduced in v0.12.0
    GoVersion  string // introduced in v0.12.0
}

BuildInfo holds the aah application build information; such as BinaryName, Version and Date.

type Context Uses

type Context struct {
    // Req is HTTP request instance
    Req *ahttp.Request

    // Res is HTTP response writer compliant.
    //
    // Note 1: It is highly recommended to use `Reply()` builder for
    // composing your response.
    //
    // Note 2: If you're using `cxt.Res` directly, don't forget to call
    // `Reply().Done()`; so that aah will not intervene with your
    // response.
    Res ahttp.ResponseWriter
    // contains filtered or unexported fields
}

Context type for aah framework, gets embedded in application controller.

Note: this is not standard package `context.Context`.

func (*Context) Abort Uses

func (ctx *Context) Abort()

Abort method sets the abort to true. It means framework will not proceed with next middleware, next interceptor or action based on context it being used. Contexts:

   1) If it's called in the middleware, then middleware chain stops;
	framework starts processing response.
   2) If it's called in Before interceptor then Before<Action> interceptor,
	mapped <Action>, After<Action> interceptor and After interceptor will not
	execute; framework starts processing response.
   3) If it's called in Mapped <Action> then After<Action> interceptor and
	After interceptor will not execute; framework starts processing response.

func (*Context) AddViewArg Uses

func (ctx *Context) AddViewArg(key string, value interface{}) *Context

AddViewArg method adds given key and value into `viewArgs`. These view args values accessible on templates. Chained call is possible.

func (*Context) Get Uses

func (ctx *Context) Get(key string) interface{}

Get method returns the value for the given key, otherwise it returns nil.

func (*Context) IsStaticRoute Uses

func (ctx *Context) IsStaticRoute() bool

IsStaticRoute method returns true if it's static route otherwise false.

func (*Context) Log Uses

func (ctx *Context) Log() log.Loggerer

Log method adds field `Request ID` into current log context and returns the logger.

func (*Context) Msg Uses

func (ctx *Context) Msg(key string, args ...interface{}) string

Msg method returns the i18n value for given key otherwise empty string returned.

func (*Context) Msgl Uses

func (ctx *Context) Msgl(locale *ahttp.Locale, key string, args ...interface{}) string

Msgl method returns the i18n value for given local and key otherwise empty string returned.

func (*Context) Reply Uses

func (ctx *Context) Reply() *Reply

Reply method gives you control and convenient way to write a response effectively.

func (*Context) RouteURL Uses

func (ctx *Context) RouteURL(routeName string, args ...interface{}) string

RouteURL method returns the URL for given route name and args. See `router.Domain.RouteURL` for more information.

func (*Context) RouteURLNamedArgs Uses

func (ctx *Context) RouteURLNamedArgs(routeName string, args map[string]interface{}) string

RouteURLNamedArgs method returns the URL for given route name and key-value paris. See `router.Domain.RouteURLNamedArgs` for more information.

func (*Context) Session Uses

func (ctx *Context) Session() *session.Session

Session method always returns `session.Session` object. Use `Session.IsNew` to identify whether sesison is newly created or restored from the request which was already created.

func (*Context) Set Uses

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

Set method is used to set value for the given key in the current request flow.

func (*Context) SetMethod Uses

func (ctx *Context) SetMethod(method string)

SetMethod method is to set the request `Method` to change the behaviour of request routing. Ideal for URL rewrting.

Note: This method only takes effect on `OnRequest` HTTP server event.

func (*Context) SetURL Uses

func (ctx *Context) SetURL(pathURL string)

SetURL method is to set the request URL to change the behaviour of request routing. Ideal for URL rewrting. URL can be relative or absolute URL.

Note: This method only takes effect on `OnRequest` HTTP server event.

func (*Context) Subdomain Uses

func (ctx *Context) Subdomain() string

Subdomain method returns the subdomain from the incoming request if available as per routes.conf. Otherwise empty string.

func (*Context) Subject Uses

func (ctx *Context) Subject() *security.Subject

Subject method the subject (aka application user) of current request.

func (*Context) ViewArgs Uses

func (ctx *Context) ViewArgs() map[string]interface{}

ViewArgs method returns aah framework and request related info that can be used in template or view rendering, etc.

type Data Uses

type Data map[string]interface{}

Data type used for convenient data type of map[string]interface{}

func (Data) MarshalXML Uses

func (d Data) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML method is to marshal `aah.Data` into XML.

type Error Uses

type Error struct {
    Reason  error       `json:"-" xml:"-"`
    Code    int         `json:"code,omitempty" xml:"code,omitempty"`
    Message string      `json:"message,omitempty" xml:"message,omitempty"`
    Data    interface{} `json:"data,omitempty" xml:"data,omitempty"`
}

Error structure is used to represent the error information in aah framework.

func (*Error) Error Uses

func (e *Error) Error() string

Error method is to comply error interface.

type ErrorHandler Uses

type ErrorHandler interface {
    // HandleError method is to handle controller specific errors
    //
    //  - Returns `true` if one or more errors are handled. aah just writes the reply on the wire.
    //
    //  - Return `false` if one or more errors could not be handled. aah propagates the error(s)
    // further onto centralized error handler. If not handled, then finally default
    // error handler takes control.
    HandleError(err *Error) bool
}

ErrorHandler is an interface to implement controller level error handling

type ErrorHandlerFunc Uses

type ErrorHandlerFunc func(ctx *Context, err *Error) bool

ErrorHandlerFunc is a function type. It is used to define a centralized error handler for an application.

- Returns `true` when one or more errors are handled. aah just writes the reply on the wire.

- Returns `false' when one or more errors could not be handled. aah propagates the error(s)

to default error handler.

type Event Uses

type Event struct {
    Name string
    Data interface{}
}

Event type holds the details of single event.

type EventCallback Uses

type EventCallback struct {
    Callback EventCallbackFunc
    CallOnce bool
    // contains filtered or unexported fields
}

EventCallback type is store particular callback in priority for calling sequance.

type EventCallbackFunc Uses

type EventCallbackFunc func(e *Event)

EventCallbackFunc is signature of event callback function.

type EventCallbacks Uses

type EventCallbacks []EventCallback

EventCallbacks type is slice of `EventCallback` type.

type EventStore Uses

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

EventStore type holds all the events belongs to aah application.

func (*EventStore) IsEventExists Uses

func (es *EventStore) IsEventExists(eventName string) bool

IsEventExists method returns true if given event is exists in the event store otherwise false.

func (*EventStore) Publish Uses

func (es *EventStore) Publish(e *Event)

Publish method publishes events to subscribed callbacks asynchronously. It means each subscribed callback executed via goroutine.

func (*EventStore) PublishSync Uses

func (es *EventStore) PublishSync(e *Event)

PublishSync method publishes events to subscribed callbacks synchronously.

func (*EventStore) Subscribe Uses

func (es *EventStore) Subscribe(event string, ec EventCallback)

Subscribe method is to subscribe any event with event callback info.

func (*EventStore) SubscriberCount Uses

func (es *EventStore) SubscriberCount(eventName string) int

SubscriberCount method returns subscriber count for given event name.

func (*EventStore) Unsubscribe Uses

func (es *EventStore) Unsubscribe(event string, callback EventCallbackFunc)

Unsubscribe method is to unsubscribe any callback from event store by event.

type HTTPEngine Uses

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

HTTPEngine holds the implementation handling HTTP request, response, middlewares, interceptors, etc.

func (*HTTPEngine) Handle Uses

func (e *HTTPEngine) Handle(w http.ResponseWriter, r *http.Request)

Handle method is HTTP handler for aah application.

func (*HTTPEngine) Log Uses

func (e *HTTPEngine) Log() log.Loggerer

Log method returns HTTP engine logger.

func (*HTTPEngine) Middlewares Uses

func (e *HTTPEngine) Middlewares(middlewares ...MiddlewareFunc)

Middlewares method adds given middleware into middleware stack

func (*HTTPEngine) OnHeaderReply Uses

func (e *HTTPEngine) OnHeaderReply(sef EventCallbackFunc)

OnHeaderReply method is to subscribe to aah HTTP engine `OnHeaderReply` extension point. `OnHeaderReply` called for every reply from aah server.

	Except when

 		1) `Reply().Done()`,

 		2) `Reply().Redirect(...)` is called.

Refer `aah.Reply().Done()` godoc for more info.

func (*HTTPEngine) OnPostAuth Uses

func (e *HTTPEngine) OnPostAuth(sef EventCallbackFunc)

OnPostAuth method is to subscribe to aah application `OnPreAuth` event. `OnPostAuth` event pubished right after the aah server authenticates & authorizes an incoming request.

func (*HTTPEngine) OnPostReply Uses

func (e *HTTPEngine) OnPostReply(sef EventCallbackFunc)

OnPostReply method is to subscribe to aah HTTP engine `OnPostReply` extension point. `OnPostReply` called for every reply from aah server.

	Except when

 		1) `Reply().Done()`,

 		2) `Reply().Redirect(...)` is called.

Refer `aah.Reply().Done()` godoc for more info.

func (*HTTPEngine) OnPreAuth Uses

func (e *HTTPEngine) OnPreAuth(sef EventCallbackFunc)

OnPreAuth method is to subscribe to aah application `OnPreAuth` event. `OnPreAuth` event pubished right before the aah server authenticates & authorizes an incoming request.

func (*HTTPEngine) OnPreReply Uses

func (e *HTTPEngine) OnPreReply(sef EventCallbackFunc)

OnPreReply method is to subscribe to aah HTTP engine `OnPreReply` extension point. `OnPreReply` called for every reply from aah server.

	Except when

 		1) `Reply().Done()`,

 		2) `Reply().Redirect(...)` is called.

Refer `aah.Reply().Done()` godoc for more info.

func (*HTTPEngine) OnRequest Uses

func (e *HTTPEngine) OnRequest(sef EventCallbackFunc)

OnRequest method is to subscribe to aah HTTP engine `OnRequest` extension point. `OnRequest` called for every incoming HTTP request.

The `aah.Context` object passed to the extension functions is decorated with the `ctx.SetURL()` and `ctx.SetMethod()` methods. Calls to these methods will impact how the request is routed and can be used for rewrite rules.

Note: Route is not yet populated/evaluated at this point.

type Middleware Uses

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

Middleware struct is to implement aah framework middleware chain.

func (*Middleware) Next Uses

func (mw *Middleware) Next(ctx *Context)

Next method calls next middleware in the chain if available.

type MiddlewareFunc Uses

type MiddlewareFunc func(ctx *Context, m *Middleware)

MiddlewareFunc func type is aah framework middleware signature.

func ToMiddleware Uses

func ToMiddleware(handler interface{}) MiddlewareFunc

ToMiddleware method expands the possibilities. It helps aah users to register the third-party or your own net/http middleware into `aah.MiddlewareFunc`.

It is highly recommended to refactored to `aah.MiddlewareFunc`.

You can register below handler types:

  1) aah.ToMiddleware(h http.Handler)

  2) aah.ToMiddleware(h http.HandlerFunc)

  3) aah.ToMiddleware(func(w http.ResponseWriter, r *http.Request))

type MinifierFunc Uses

type MinifierFunc func(contentType string, w io.Writer, r io.Reader) error

MinifierFunc is to minify the HTML buffer and write the response into writer.

type Render Uses

type Render interface {
    Render(io.Writer) error
}

Render interface to various rendering classifcation for HTTP responses.

type RenderFunc Uses

type RenderFunc func(w io.Writer) error

RenderFunc type is an adapter to allow the use of regular function as custom Render.

func (RenderFunc) Render Uses

func (rf RenderFunc) Render(w io.Writer) error

Render method is implementation of Render interface in the adapter type.

type Reply Uses

type Reply struct {
    Rdr      Render
    Code     int
    ContType string
    // contains filtered or unexported fields
}

Reply gives you control and convenient way to write a response effectively.

func (*Reply) Accepted Uses

func (r *Reply) Accepted() *Reply

Accepted method sets the HTTP Code as 202 RFC 7231, 6.3.3.

func (*Reply) BadRequest Uses

func (r *Reply) BadRequest() *Reply

BadRequest method sets the HTTP Code as 400 RFC 7231, 6.5.1.

func (*Reply) Binary Uses

func (r *Reply) Binary(b []byte) *Reply

Binary method writes given bytes into response. It auto-detects the content type of the given bytes if header `Content-Type` is not set.

func (*Reply) Body Uses

func (r *Reply) Body() *bytes.Buffer

Body method returns the response body buffer.

It might be nil if the -

  1) Response was written successfully on the wire

  2) Response is not yet rendered

  3) Static files, since response is written via `http.ServeContent`

func (*Reply) Conflict Uses

func (r *Reply) Conflict() *Reply

Conflict method sets the HTTP Code as 409 RFC 7231, 6.5.8.

func (*Reply) ContentType Uses

func (r *Reply) ContentType(contentType string) *Reply

ContentType method sets given Content-Type string for the response. Also Reply instance provides easy to use method for very frequently used Content-Type(s).

By default aah framework try to determine response 'Content-Type' from 'ahttp.Request.AcceptContentType()'.

func (*Reply) Cookie Uses

func (r *Reply) Cookie(cookie *http.Cookie) *Reply

Cookie method adds the give HTTP cookie into response.

func (*Reply) Created Uses

func (r *Reply) Created() *Reply

Created method sets the HTTP Code as 201 RFC 7231, 6.3.2.

func (*Reply) DisableGzip Uses

func (r *Reply) DisableGzip() *Reply

DisableGzip method allows you disable Gzip for the reply. By default every response is gzip compressed if the client supports it and gzip enabled in app config.

func (*Reply) Done Uses

func (r *Reply) Done() *Reply

Done method is used to indicate response has already been written using `aah.Context.Res` so no further action is needed from framework.

Note: Framework doesn't intervene with response if this method called by aah user.

func (*Reply) Error Uses

func (r *Reply) Error(err *Error) *Reply

Error method is used send an error reply, which is handled by aah error handling mechanism.

More Info: https://docs.aahframework.org/error-handling.html

func (*Reply) File Uses

func (r *Reply) File(file string) *Reply

File method send the given as file to client. It auto-detects the content type of the file if `Content-Type` is not set.

Note: If give filepath is relative path then application base directory is used as prefix.

func (*Reply) FileDownload Uses

func (r *Reply) FileDownload(file, targetName string) *Reply

FileDownload method send the given as file to client as a download. It sets the `Content-Disposition` as `attachment` with given target name and auto-detects the content type of the file if `Content-Type` is not set.

func (*Reply) FileInline Uses

func (r *Reply) FileInline(file, targetName string) *Reply

FileInline method send the given as file to client to display. For e.g.: display within the browser. It sets the `Content-Disposition` as `inline` with given target name and auto-detects the content type of the file if `Content-Type` is not set.

func (*Reply) Forbidden Uses

func (r *Reply) Forbidden() *Reply

Forbidden method sets the HTTP Code as 403 RFC 7231, 6.5.3.

func (*Reply) Found Uses

func (r *Reply) Found() *Reply

Found method sets the HTTP Code as 302 RFC 7231, 6.4.3.

func (*Reply) FromReader Uses

func (r *Reply) FromReader(reader io.Reader) *Reply

FromReader method reads the data from given reader and writes into response. It auto-detects the content type of the file if `Content-Type` is not set.

Note: Method will close the reader after serving if it's satisfies the `io.Closer`.

func (*Reply) HTML Uses

func (r *Reply) HTML(data Data) *Reply

HTML method renders given data with auto mapped template name and layout by framework. Also it sets HTTP 'Content-Type' as 'text/html; charset=utf-8'.

aah renders the view template based on -

1) path 'Namespace/Sub-package' of Controller,

2) path 'Controller.Action',

3) view extension 'view.ext' and

4) case sensitive 'view.case_sensitive' from aah.conf

5) default layout is 'master.html'

For e.g.:
  Namespace/Sub-package: frontend
  Controller: App
  Action: Login
  view.ext: html

  Outcome view template path => /views/pages/frontend/app/login.html

func (*Reply) HTMLf Uses

func (r *Reply) HTMLf(filename string, data Data) *Reply

HTMLf method renders based on given filename and data. Refer `Reply.HTML(...)` method.

func (*Reply) HTMLl Uses

func (r *Reply) HTMLl(layout string, data Data) *Reply

HTMLl method renders based on given layout and data. Refer `Reply.HTML(...)` method.

func (*Reply) HTMLlf Uses

func (r *Reply) HTMLlf(layout, filename string, data Data) *Reply

HTMLlf method renders based on given layout, filename and data. Refer `Reply.HTML(...)` method.

func (*Reply) Header Uses

func (r *Reply) Header(key, value string) *Reply

Header method sets the given header and value for the response. If value == "", then this method deletes the header.

Note: It overwrites existing header value if it's present.

func (*Reply) HeaderAppend Uses

func (r *Reply) HeaderAppend(key, value string) *Reply

HeaderAppend method appends the given header and value for the response.

Note: It just appends to it. It does not overwrite existing header.

func (*Reply) InternalServerError Uses

func (r *Reply) InternalServerError() *Reply

InternalServerError method sets the HTTP Code as 500 RFC 7231, 6.6.1.

func (*Reply) IsContentTypeSet Uses

func (r *Reply) IsContentTypeSet() bool

IsContentTypeSet method returns true if Content-Type is set otherwise false.

func (*Reply) JSON Uses

func (r *Reply) JSON(data interface{}) *Reply

JSON method renders given data as JSON response and it sets HTTP 'Content-Type' as 'application/json; charset=utf-8'.

func (*Reply) JSONP Uses

func (r *Reply) JSONP(data interface{}, callback string) *Reply

JSONP method renders given data as JSONP response with callback and it sets HTTP 'Content-Type' as 'application/javascript; charset=utf-8'.

func (*Reply) JSONSecure Uses

func (r *Reply) JSONSecure(data interface{}) *Reply

JSONSecure method renders given data as Secure JSON into response. and it sets HTTP 'Content-Type' as 'application/json; charset=utf-8'.

See config `render.secure_json.prefix`.

func (*Reply) MethodNotAllowed Uses

func (r *Reply) MethodNotAllowed() *Reply

MethodNotAllowed method sets the HTTP Code as 405 RFC 7231, 6.5.5.

func (*Reply) MovedPermanently Uses

func (r *Reply) MovedPermanently() *Reply

MovedPermanently method sets the HTTP Code as 301 RFC 7231, 6.4.2.

func (*Reply) NoContent Uses

func (r *Reply) NoContent() *Reply

NoContent method sets the HTTP Code as 204 RFC 7231, 6.3.5.

func (*Reply) NotAcceptable Uses

func (r *Reply) NotAcceptable() *Reply

NotAcceptable method sets the HTTP Code as 406 RFC 7231, 6.5.6

func (*Reply) NotFound Uses

func (r *Reply) NotFound() *Reply

NotFound method sets the HTTP Code as 404 RFC 7231, 6.5.4.

func (*Reply) Ok Uses

func (r *Reply) Ok() *Reply

Ok method sets the HTTP Code as 200 RFC 7231, 6.3.1.

func (*Reply) Redirect Uses

func (r *Reply) Redirect(redirectURL string) *Reply

Redirect method redirects to given redirect URL with status 302.

func (*Reply) RedirectWithStatus Uses

func (r *Reply) RedirectWithStatus(redirectURL string, code int) *Reply

RedirectWithStatus method redirects to given redirect URL and status code.

func (*Reply) Render Uses

func (r *Reply) Render(rdr Render) *Reply

Render method is used render custom implementation using interface `aah.Render`.

func (*Reply) ServiceUnavailable Uses

func (r *Reply) ServiceUnavailable() *Reply

ServiceUnavailable method sets the HTTP Code as 503 RFC 7231, 6.6.4.

func (*Reply) Status Uses

func (r *Reply) Status(code int) *Reply

Status method sets the HTTP Code code for the response. Also Reply instance provides easy to use method for very frequently used HTTP Status Codes reference: http://www.restapitutorial.com/httpCodecodes.html

func (*Reply) TemporaryRedirect Uses

func (r *Reply) TemporaryRedirect() *Reply

TemporaryRedirect method sets the HTTP Code as 307 RFC 7231, 6.4.7.

func (*Reply) Text Uses

func (r *Reply) Text(format string, values ...interface{}) *Reply

Text method renders given data as Plain Text response with given values and it sets HTTP Content-Type as 'text/plain; charset=utf-8'.

func (*Reply) Unauthorized Uses

func (r *Reply) Unauthorized() *Reply

Unauthorized method sets the HTTP Code as 401 RFC 7235, 3.1.

func (*Reply) UnsupportedMediaType Uses

func (r *Reply) UnsupportedMediaType() *Reply

UnsupportedMediaType method sets the HTTP Code as 415 RFC 7231, 6.5.13

func (*Reply) XML Uses

func (r *Reply) XML(data interface{}) *Reply

XML method renders given data as XML response and it sets HTTP Content-Type as 'application/xml; charset=utf-8'.

Directories

PathSynopsis
ahttpPackage ahttp is to cater HTTP helper methods for aah framework.
ainspPackage ainsp is a Go ast library for aah framework, it does inspect and discovers the Go `struct` which embeds particular type `struct`.
aruntimePackage aruntime provides aah runtime capabilities to collect debug stacktrace, goroutines diagnosis profiling.
aruntime/diagnosisPackage diagnosis brings feature of aah application profiling to do various diagnosis.
cachePackage cache provides simple and extensible cache feature for aah application.
configPackage config is nice and handy layer built around `forge` config syntax; which is similar to HOCON syntax.
consolePackage console provides a feature to implement CLI commands into your aah application easily and extensible.
essentialsPackage ess provides a essentials and helper for the application development and usage.
i18nPackage i18n is internationalization and localization support for aah framework.
internal/settings
internal/util
logPackage log simple logger and provides capabilities to fulfill application use cases.
routerPackage router provides routing implementation for aah framework.
securityPackage security houses all the application security implementation Authentication, Authorization, Session Management, CSRF, Security Headers, etc.) by aah framework.
security/acrypto
security/anticsrf
security/authc
security/authz
security/cookie
security/scheme
security/sessionPackage session provides HTTP state management library for aah framework.
valparPackage valpar provides feature of request value parsing, handling, binding and validating.
vfsPackage vfs provides Virtual FileSystem (VFS) capability.
viewPackage view is implementation of aah framework view engine using Go Template engine.
wsPackage ws is a WebSocket library for aah framework (RFC 6455 compliant).

Package aah imports 52 packages (graph) and is imported by 2 packages. Updated 2019-11-21. Refresh now. Tools for package owners.