aah

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2017 License: MIT Imports: 34 Imported by: 0

README

aah framework

Build Status codecov Go Report Card Powered by Go Version GoDoc License

v0.4.1 pre-release and tagged on Apr 15, 2017

aah - A scalable, performant, rapid development Web framework for Go.

Actively working on documentation of aah framework. However you can give it try and share your feedback.

Stay tuned on -

  • Gitter - chat online
  • Twitter - Twitter Follow

Installation aah framework

Version (pre-release)
# install the aah framework
# it installs framework and aah CLI tool
go get -u aahframework.org/tools.v0/aah

See official website - Work-in-progress.

Documentation

Overview

Package aah is A scalable, performant, rapid development Web framework for Go https://aahframework.org

Index

Constants

View Source
const (
	// EventOnInit event is fired right after aah application config is initialized.
	EventOnInit = "OnInit"

	// EventOnStart event is fired before HTTP/Unix listener starts
	EventOnStart = "OnStart"

	// EventOnShutdown event is fired when server recevies interrupt or kill command.
	EventOnShutdown = "OnShutdown"

	// EventOnRequest event is fired when server recevies incoming request.
	EventOnRequest = "OnRequest"

	// EventOnPreReply event is fired when before server writes the reply on the wire.
	// Except when 1) Static file request, 2) `Reply().Done()`
	// 3) `Reply().Redirect(...)` is called. Refer `aah.Reply.Done()` godoc for more info.
	EventOnPreReply = "OnPreReply"

	// EventOnAfterReply event is fired when before server writes the reply on the wire.
	// Except when 1) Static file request, 2) `Reply().Done()`
	// 3) `Reply().Redirect(...)` is called. Refer `aah.Reply.Done()` godoc for more info.
	EventOnAfterReply = "OnAfterReply"
)
View Source
const Version = "0.4"

Version no. of aah framework

Variables

This section is empty.

Functions

func AddController

func AddController(c interface{}, methods []*MethodInfo)

AddController method adds given controller into controller registory. with "dereferenced" a.k.a "indirecting".

func AddSessionStore

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

AddSessionStore method allows you to add custom session store which implements `session.Storer` interface. The `name` parameter is used in aah.conf on `session.store.type = "name"`.

func AddTemplateFunc

func AddTemplateFunc(funcs template.FuncMap)

AddTemplateFunc method adds template func map into view engine.

func AddViewEngine

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

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

func AllAppProfiles

func AllAppProfiles() []string

AllAppProfiles method returns all the aah application environment profile names.

func AppBaseDir

func AppBaseDir() string

AppBaseDir method returns the application base or binary current directory

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

func AppConfig

func AppConfig() *config.Config

AppConfig method returns aah application configuration instance.

func AppDateFormat

func AppDateFormat() string

AppDateFormat method returns aah application date format

func AppDateTimeFormat

func AppDateTimeFormat() string

AppDateTimeFormat method returns aah application date format

func AppDefaultI18nLang

func AppDefaultI18nLang() string

AppDefaultI18nLang method returns aah application i18n default language if configured other framework defaults to "en".

func AppHTTPAddress

func AppHTTPAddress() string

AppHTTPAddress method returns aah application HTTP address otherwise empty string

func AppHTTPPort

func AppHTTPPort() string

AppHTTPPort method returns aah application HTTP port number if available or if empty returns port 80; otherwise returns default port number 8080.

func AppI18n

func AppI18n() *i18n.I18n

AppI18n method returns aah application I18n store instance.

func AppI18nLocales

func AppI18nLocales() []string

AppI18nLocales returns all the loaded locales from i18n store

func AppImportPath

func AppImportPath() string

AppImportPath method returns the application Go import path.

func AppIsSSLEnabled

func AppIsSSLEnabled() bool

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

func AppName

func AppName() string

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

func AppProfile

func AppProfile() string

AppProfile returns aah application configuration profile name For e.g.: dev, prod, etc. Default is `dev`

func AppRouter

func AppRouter() *router.Router

AppRouter method returns aah application router instance.

func AppSecurity

func AppSecurity() *security.Security

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

func AppSessionManager

func AppSessionManager() *session.Manager

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

func AppViewEngine

func AppViewEngine() view.Enginer

AppViewEngine method returns aah application view Engine instance.

func Init

func Init(importPath string)

Init method initializes `aah` application, if anything goes wrong during initialize process, it will log it as fatal msg and exit.

func Middlewares

func Middlewares(middlewares ...MiddlewareFunc)

Middlewares method adds given middleware into middleware stack

func OnAfterReply

func OnAfterReply(sef EventCallbackFunc)

OnAfterReply method is to subscribe to aah server `OnAfterReply` extension point. `OnAfterReply` called for every reply from aah server.

Except when 1) Static file request, 2) `Reply().Done()` 3) `Reply().Redirect(...)` is called. Refer `aah.Reply.Done()` godoc for more info.

func OnInit

func 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 OnPreReply

func OnPreReply(sef EventCallbackFunc)

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

Except when 1) Static file request, 2) `Reply().Done()` 3) `Reply().Redirect(...)` is called. Refer `aah.Reply.Done()` godoc for more info.

func OnRequest

func OnRequest(sef EventCallbackFunc)

OnRequest method is to subscribe to aah server `OnRequest` extension point. `OnRequest` called for every incoming 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.

Route is not yet processed at this point.

func OnShutdown

func OnShutdown(ecb EventCallbackFunc, priority ...int)

OnShutdown method is to subscribe to aah application `OnShutdown` event. `OnShutdown` event pubished right before the aah server is stopped Listening and serving request.

func OnStart

func OnStart(ecb EventCallbackFunc, priority ...int)

OnStart method is to subscribe to aah application `OnStart` event. `OnStart` event pubished right before the aah server listen and serving request.

func PublishEvent

func PublishEvent(eventName string, data interface{})

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

func PublishEventSync

func PublishEventSync(eventName string, data interface{})

PublishEventSync method publishes events to subscribed callbacks synchronously.

func SetAppBuildInfo

func SetAppBuildInfo(bi *BuildInfo)

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

func SetAppProfile

func SetAppProfile(profile string) error

SetAppProfile method sets given profile as current aah application profile.

For Example:

aah.SetAppProfile("prod")

func Shutdown

func Shutdown()

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

Method performs:

  • Graceful server shutdown with timeout by `server.timeout.grace_shutdown`
  • Publishes `OnShutdown` event
  • Exits program with code 0

Note: This applicable only to go1.8 and above.

func Start

func Start()

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

func SubscribeEvent

func SubscribeEvent(eventName string, ec EventCallback)

SubscribeEvent method is to subscribe to new or existing event.

func UnsubscribeEvent

func UnsubscribeEvent(eventName string, ec EventCallback)

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

func UnsubscribeEventf

func UnsubscribeEventf(eventName string, ec EventCallbackFunc)

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

Types

type BuildInfo

type BuildInfo struct {
	BinaryName string
	Version    string
	Date       string
}

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

func AppBuildInfo

func AppBuildInfo() *BuildInfo

AppBuildInfo method return user application version no.

type Bytes

type Bytes struct {
	Data []byte
}

Bytes renders the bytes into response.

func (*Bytes) Render

func (b *Bytes) Render(w io.Writer) error

Render method writes XML to HTTP response.

type Context

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

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

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

func (*Context) Abort

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

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) Cookie

func (ctx *Context) Cookie(name string) (*http.Cookie, error)

Cookie method returns a named cookie from HTTP request otherwise error.

func (*Context) Cookies

func (ctx *Context) Cookies() []*http.Cookie

Cookies method returns all the cookies from HTTP request.

func (*Context) Msg

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

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

func (ctx *Context) Reply() *Reply

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

func (*Context) Reset

func (ctx *Context) Reset()

Reset method resets context instance for reuse.

func (*Context) ReverseURL

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

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

func (*Context) ReverseURLm

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

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

func (*Context) Session

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) SetMethod

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` server event.

func (*Context) SetURL

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` server event.

func (*Context) ViewArgs

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

type Data map[string]interface{}

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

type Event

type Event struct {
	Name string
	Data interface{}
}

Event type holds the details of event generated.

type EventCallback

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

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

type EventCallbackFunc

type EventCallbackFunc func(e *Event)

EventCallbackFunc is signature of event callback function.

type EventCallbacks

type EventCallbacks []EventCallback

EventCallbacks type is slice of `EventCallback` type.

func (EventCallbacks) Len

func (ec EventCallbacks) Len() int

Sort interface for EventCallbacks

func (EventCallbacks) Less

func (ec EventCallbacks) Less(i, j int) bool

func (EventCallbacks) Swap

func (ec EventCallbacks) Swap(i, j int)

type EventStore

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

EventStore type holds all the events belongs to aah application.

func AppEventStore

func AppEventStore() *EventStore

AppEventStore method returns aah application event store.

func (*EventStore) IsEventExists

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

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

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

PublishSync method publishes events to subscribed callbacks synchronously.

func (*EventStore) Subscribe

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

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

func (*EventStore) SubscriberCount

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

SubscriberCount method returns subscriber count for given event name.

func (*EventStore) Unsubscribe

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

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

type File

type File struct {
	Data io.ReadCloser
}

File renders given ReadCloser into response and closes the file.

func (*File) Render

func (f *File) Render(w io.Writer) error

Render method writes File to HTTP response.

type HTML

type HTML struct {
	Template *template.Template
	Layout   string
	Filename string
	ViewArgs Data
}

HTML renders the given HTML into response with given model data.

func (*HTML) Render

func (h *HTML) Render(w io.Writer) error

Render method renders the HTML template into given writer.

type JSON

type JSON struct {
	IsJSONP  bool
	Callback string
	Data     interface{}
}

JSON renders the response JSON content.

func (*JSON) Render

func (j *JSON) Render(w io.Writer) error

Render method writes JSON to HTTP response.

type MethodInfo

type MethodInfo struct {
	Name       string
	Parameters []*ParameterInfo
}

MethodInfo holds information of single method information in the controller.

type Middleware

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

Middleware struct is to implement aah framework middleware chain.

func (*Middleware) Next

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

Next method calls next middleware in the chain if available.

type MiddlewareFunc

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

MiddlewareFunc func type is aah framework middleware signature.

func ToMiddleware

func ToMiddleware(handler interface{}) MiddlewareFunc

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

You can register below handler types: 1) aah.ToMiddleware(h http.Handler) 2) aah.ToMiddleware(func(w http.ResponseWriter, r *http.Request))

type ParameterInfo

type ParameterInfo struct {
	Name string
	Type reflect.Type
}

ParameterInfo holds information of single parameter in the method.

type Render

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

Render interface

type Reply

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

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

func NewReply

func NewReply() *Reply

NewReply method returns the new instance on reply builder.

func (*Reply) Accepted

func (r *Reply) Accepted() *Reply

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

func (*Reply) BadRequest

func (r *Reply) BadRequest() *Reply

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

func (*Reply) Bytes

func (r *Reply) Bytes(contentType string, data []byte) *Reply

Bytes method writes the given bytes into response with given 'Content-Type'.

func (*Reply) Conflict

func (r *Reply) Conflict() *Reply

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

func (*Reply) ContentType

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

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

Cookie method adds the give HTTP cookie into response.

func (*Reply) Created

func (r *Reply) Created() *Reply

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

func (*Reply) Done

func (r *Reply) Done() *Reply

Done method concludes middleware flow, action flow by returning control over to framework and informing that reply has already been sent via `aahContext.Res` and that no further action is needed.

func (*Reply) File

func (r *Reply) File(filename string, file io.ReadCloser) *Reply

File method writes the given file into response and close the file after write. Also it sets HTTP 'Content-Type' as 'application/octet-stream' and adds the header 'Content-Disposition' as 'attachment' with given filename. Note: Method does close the given 'io.ReadCloser' after writing a response.

func (*Reply) FileInline

func (r *Reply) FileInline(filename string, file io.ReadCloser) *Reply

FileInline method writes the given file into response and close the file after write. Also it sets HTTP 'Content-Type' as 'application/octet-stream' and adds the header 'Content-Disposition' as 'inline' with given filename. Note: Method does close the given 'io.ReadCloser' after writing a response.

func (*Reply) Forbidden

func (r *Reply) Forbidden() *Reply

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

func (*Reply) Found

func (r *Reply) Found() *Reply

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

func (*Reply) HTML

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'. By default aah framework renders the template based on

  1. path 'Controller.Action',

  2. template extension 'template.ext' and

  3. case sensitive 'template.case_sensitive' from aah.conf

  4. default layout is 'master' E.g.: Controller: App Action: Login template.ext: html

    template => /views/pages/app/login.html => /views/pages/App/Login.html

func (*Reply) HTMLl

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

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

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

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

HeaderAppend method appends the given header and value for the response. Note: It does not overwrite existing header, it just appends to it.

func (*Reply) InternalServerError

func (r *Reply) InternalServerError() *Reply

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

func (*Reply) IsContentTypeSet

func (r *Reply) IsContentTypeSet() bool

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

func (*Reply) JSON

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

JSON method renders given data as JSON response. Also it sets HTTP 'Content-Type' as 'application/json; charset=utf-8'. Response rendered pretty if 'render.pretty' is true.

func (*Reply) JSONP

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

JSONP method renders given data as JSONP response with callback. Also it sets HTTP 'Content-Type' as 'application/json; charset=utf-8'. Response rendered pretty if 'render.pretty' is true.

func (*Reply) MethodNotAllowed

func (r *Reply) MethodNotAllowed() *Reply

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

func (*Reply) MovedPermanently

func (r *Reply) MovedPermanently() *Reply

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

func (*Reply) NoContent

func (r *Reply) NoContent() *Reply

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

func (*Reply) NotFound

func (r *Reply) NotFound() *Reply

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

func (*Reply) Ok

func (r *Reply) Ok() *Reply

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

func (*Reply) Redirect

func (r *Reply) Redirect(redirectURL string)

Redirect method redirect the to given redirect URL with status 302 and it does not provide option for chain call.

func (*Reply) Redirects

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

Redirects method redirect the to given redirect URL and status code. It does not provide option for chain call.

func (*Reply) ServiceUnavailable

func (r *Reply) ServiceUnavailable() *Reply

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

func (*Reply) Status

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

func (r *Reply) TemporaryRedirect() *Reply

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

func (*Reply) Text

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

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

func (*Reply) Unauthorized

func (r *Reply) Unauthorized() *Reply

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

func (*Reply) XML

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

XML method renders given data as XML response. Also it sets HTTP Content-Type as 'application/xml; charset=utf-8'. Response rendered pretty if 'render.pretty' is true.

type Text

type Text struct {
	Format string
	Values []interface{}
}

Text renders the response as plain text

func (*Text) Render

func (t *Text) Render(w io.Writer) error

Render method writes Text to HTTP response.

type XML

type XML struct {
	Data interface{}
}

XML renders the response XML content.

func (*XML) Render

func (x *XML) Render(w io.Writer) error

Render method writes XML to HTTP response.

Jump to

Keyboard shortcuts

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