revel

package module
Version: v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2020 License: MIT Imports: 48 Imported by: 2,729

README

Revel Framework

Build Status License Go Report Card

A high productivity, full-stack web framework for the Go language.

Current Version: 1.0.0 (2020-07-11)

Supports go.mod package management

Quick Start

Install Revel:

go get -u github.com/revel/cmd/revel

Create & Run your app:

revel new -a my-app -r

Open http://localhost:9000 in your browser and you should see "It works!"

Community

Learn More

Contributing

Contributors

Documentation

Index

Constants

View Source
const (
	DefaultDateFormat     = "2006-01-02"
	DefaultDateTimeFormat = "2006-01-02 15:04"
)

Revel's default date and time constants

View Source
const (
	TEST_MODE_FLAG   = "testModeFlag"
	SPECIAL_USE_FLAG = "specialUseFlag"
)
View Source
const (
	ENGINE_RESPONSE_STATUS
	ENGINE_WRITER
	ENGINE_PARAMETERS
	ENGINE_PATH
	ENGINE_REQUEST
	ENGINE_RESPONSE
)
View Source
const (
	/* HTTP Engine Type Values Starts at 1000 */
	HTTP_QUERY           = ENGINE_PARAMETERS
	HTTP_PATH            = ENGINE_PATH
	HTTP_BODY            = iota + 1000
	HTTP_FORM            = iota + 1000
	HTTP_MULTIPART_FORM  = iota + 1000
	HTTP_METHOD          = iota + 1000
	HTTP_REQUEST_URI     = iota + 1000
	HTTP_REQUEST_CONTEXT = iota + 1000
	HTTP_REMOTE_ADDR     = iota + 1000
	HTTP_HOST            = iota + 1000
	HTTP_URL             = iota + 1000
	HTTP_SERVER_HEADER   = iota + 1000
	HTTP_STREAM_WRITER   = iota + 1000
	HTTP_WRITER          = ENGINE_WRITER
)
View Source
const (
	None               = 0
	IPAny              = 1
	IPv4               = 32 // IPv4 (32 chars)
	IPv6               = 39 // IPv6(39 chars)
	IPv4MappedIPv6     = 45 // IP4-mapped IPv6 (45 chars) , Ex) ::FFFF:129.144.52.38
	IPv4CIDR           = IPv4 + 3
	IPv6CIDR           = IPv6 + 3
	IPv4MappedIPv6CIDR = IPv4MappedIPv6 + 3
)
View Source
const (
	NORMAL = 0
	STRICT = 4
)

NORMAL BenchmarkRegex-8 2000000000 0.24 ns/op STRICT BenchmarkLoop-8 2000000000 0.01 ns/op

View Source
const (
	ONLY_FILENAME       = 0
	ALLOW_RELATIVE_PATH = 1
)
View Source
const (
	// Version current Revel version
	Version = "1.0.0"

	// BuildDate latest commit/release date
	BuildDate = "2020-07-11"

	// MinimumGoVersion minimum required Go version for Revel
	MinimumGoVersion = ">= go1.12"
)
View Source
const (
	// CurrentLocaleViewArg the key for the current locale view arg value
	CurrentLocaleViewArg = "currentLocale"
)
View Source
const (
	// DefaultFileContentType Revel's default response content type
	DefaultFileContentType = "application/octet-stream"
)
View Source
const GO_NATIVE_SERVER_ENGINE = "go"

The server key name

View Source
const GO_TEMPLATE = "go"
View Source
const (
	// RevelImportPath Revel framework import path
	RevelImportPath = "github.com/revel/revel"
)

Variables

View Source
var (
	// These are the lookups to find a Binder for any type of data.
	// The most specific binder found will be used (Type before Kind)
	TypeBinders = make(map[reflect.Type]Binder)
	KindBinders = make(map[reflect.Kind]Binder)

	// Applications can add custom time formats to this array, and they will be
	// automatically attempted when binding a time.Time.
	TimeFormats = []string{}

	DateFormat     string
	DateTimeFormat string
	TimeZone       = time.UTC

	IntBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			if len(val) == 0 {
				return reflect.Zero(typ)
			}
			intValue, err := strconv.ParseInt(val, 10, 64)
			if err != nil {
				binderLog.Warn("IntBinder Conversion Error", "error", err)
				return reflect.Zero(typ)
			}
			pValue := reflect.New(typ)
			pValue.Elem().SetInt(intValue)
			return pValue.Elem()
		}),
		Unbind: func(output map[string]string, key string, val interface{}) {
			output[key] = fmt.Sprintf("%d", val)
		},
	}

	UintBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			if len(val) == 0 {
				return reflect.Zero(typ)
			}
			uintValue, err := strconv.ParseUint(val, 10, 64)
			if err != nil {
				binderLog.Warn("UintBinder Conversion Error", "error", err)
				return reflect.Zero(typ)
			}
			pValue := reflect.New(typ)
			pValue.Elem().SetUint(uintValue)
			return pValue.Elem()
		}),
		Unbind: func(output map[string]string, key string, val interface{}) {
			output[key] = fmt.Sprintf("%d", val)
		},
	}

	FloatBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			if len(val) == 0 {
				return reflect.Zero(typ)
			}
			floatValue, err := strconv.ParseFloat(val, 64)
			if err != nil {
				binderLog.Warn("FloatBinder Conversion Error", "error", err)
				return reflect.Zero(typ)
			}
			pValue := reflect.New(typ)
			pValue.Elem().SetFloat(floatValue)
			return pValue.Elem()
		}),
		Unbind: func(output map[string]string, key string, val interface{}) {
			output[key] = fmt.Sprintf("%f", val)
		},
	}

	StringBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			return reflect.ValueOf(val)
		}),
		Unbind: func(output map[string]string, name string, val interface{}) {
			output[name] = val.(string)
		},
	}

	// Booleans support a various value formats,
	// refer `revel.Atob` method.
	BoolBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			return reflect.ValueOf(Atob(val))
		}),
		Unbind: func(output map[string]string, name string, val interface{}) {
			output[name] = fmt.Sprintf("%t", val)
		},
	}

	PointerBinder = Binder{
		Bind: func(params *Params, name string, typ reflect.Type) reflect.Value {
			v := Bind(params, name, typ.Elem())
			if v.CanAddr() {
				return v.Addr()
			}

			return v
		},
		Unbind: func(output map[string]string, name string, val interface{}) {
			Unbind(output, name, reflect.ValueOf(val).Elem().Interface())
		},
	}

	TimeBinder = Binder{
		Bind: ValueBinder(func(val string, typ reflect.Type) reflect.Value {
			for _, f := range TimeFormats {
				if r, err := time.ParseInLocation(f, val, TimeZone); err == nil {
					return reflect.ValueOf(r)
				}
			}
			return reflect.Zero(typ)
		}),
		Unbind: func(output map[string]string, name string, val interface{}) {
			var (
				t       = val.(time.Time)
				format  = DateTimeFormat
				h, m, s = t.Clock()
			)
			if h == 0 && m == 0 && s == 0 {
				format = DateFormat
			}
			output[name] = t.Format(format)
		},
	}

	MapBinder = Binder{
		Bind:   bindMap,
		Unbind: unbindMap,
	}
)

Binders type and kind definition

View Source
var (
	NilFilter = func(_ *Controller, _ []Filter) {}
	NilChain  = []Filter{NilFilter}
)

NilFilter and NilChain are helpful in writing filter tests.

View Source
var (
	// The root log is what all other logs are branched from, meaning if you set the handler for the root
	// it will adjust all children
	RootLog = logger.New()
	// This logger is the application logger, use this for your application log messages - ie jobs and startup,
	// Use Controller.Log for Controller logging
	// The requests are logged to this logger with the context of `section:requestlog`
	AppLog = RootLog.New("module", "app")
	// This is the logger revel writes to, added log messages will have a context of module:revel in them
	// It is based off of `RootLog`
	RevelLog = RootLog.New("module", "revel")

	// System logger
	SysLog = AppLog.New("section", "system")
)

Logger

View Source
var (
	RevelConfig *model.RevelContainer
	AppName     string // e.g. "sample"
	AppRoot     string // e.g. "/app1"
	BasePath    string // e.g. "$GOPATH/src/corp/sample"
	AppPath     string // e.g. "$GOPATH/src/corp/sample/app"
	ViewsPath   string // e.g. "$GOPATH/src/corp/sample/app/views"
	ImportPath  string // e.g. "corp/sample"
	SourcePath  string // e.g. "$GOPATH/src"

	Config  *config.Context
	RunMode string // Application-defined (by default, "dev" or "prod")
	DevMode bool   // if true, RunMode is a development mode.

	// Revel installation details
	RevelPath string // e.g. "$GOPATH/src/github.com/revel/revel"

	// Where to look for templates
	// Ordered by priority. (Earlier paths take precedence over later paths.)
	CodePaths     []string // Code base directories, for modules and app
	TemplatePaths []string // Template path directories manually added

	// ConfPaths where to look for configurations
	// Config load order
	// 1. framework (revel/conf/*)
	// 2. application (conf/*)
	// 3. user supplied configs (...) - User configs can override/add any from above
	ConfPaths []string

	// Server config.
	//
	// Alert: This is how the app is configured, which may be different from
	// the current process reality.  For example, if the app is configured for
	// port 9000, HTTPPort will always be 9000, even though in dev mode it is
	// run on a random port and proxied.
	HTTPPort    int    // e.g. 9000
	HTTPAddr    string // e.g. "", "127.0.0.1"
	HTTPSsl     bool   // e.g. true if using ssl
	HTTPSslCert string // e.g. "/path/to/cert.pem"
	HTTPSslKey  string // e.g. "/path/to/key.pem"

	// All cookies dropped by the framework begin with this prefix.
	CookiePrefix string
	// Cookie domain
	CookieDomain string
	// Cookie flags
	CookieSecure   bool
	CookieSameSite http.SameSite

	// True when revel engine has been initialized (Init has returned)
	Initialized bool
)

App details

View Source
var (
	MainRouter         *Router
	MainTemplateLoader *TemplateLoader
	MainWatcher        *Watcher

	CurrentEngine    ServerEngine
	ServerEngineInit *EngineInit
)

Revel's variables server, router, etc

View Source
var (
	HdrForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
	HdrRealIP       = http.CanonicalHeaderKey("X-Real-Ip")
)
View Source
var DefaultValidationKeys map[string]map[int]string

DefaultValidationKeys register default validation keys for all calls to Controller.Validation.Func(). Map from (package).func => (line => name of first arg to Validation func) E.g. "myapp/controllers.helper" or "myapp/controllers.(*Application).Action" This is set on initialization in the generated main.go file.

View Source
var (
	ENGINE_UNKNOWN_GET = errors.New("Server Engine Invalid Get")
)
View Source
var ErrorCSSClass = "hasError"

ErrorCSSClass httml CSS error class name

View Source
var FORM_NOT_FOUND = errors.New("Form Not Found")

Filters is the default set of global filters. It may be set by the application on initialization.

View Source
var MessageFunc = Message

MessageFunc allows you to override the translation interface.

Set this to your own function that translates to the current locale. This allows you to set up your own loading and logging of translated texts.

See Message(...) in i18n.go for example of function.

View Source
var (
	Modules []*Module // The list of modules in use

)
View Source
var (
	// The functions available for use in the templates.
	TemplateFuncs = map[string]interface{}{
		"url": ReverseURL,
		"set": func(viewArgs map[string]interface{}, key string, value interface{}) template.JS {
			viewArgs[key] = value
			return template.JS("")
		},
		"append": func(viewArgs map[string]interface{}, key string, value interface{}) template.JS {
			if viewArgs[key] == nil {
				viewArgs[key] = []interface{}{value}
			} else {
				viewArgs[key] = append(viewArgs[key].([]interface{}), value)
			}
			return template.JS("")
		},
		"field": NewField,
		"firstof": func(args ...interface{}) interface{} {
			for _, val := range args {
				switch val.(type) {
				case nil:
					continue
				case string:
					if val == "" {
						continue
					}
					return val
				default:
					return val
				}
			}
			return nil
		},
		"option": func(f *Field, val interface{}, label string) template.HTML {
			selected := ""
			if f.Flash() == val || (f.Flash() == "" && f.Value() == val) {
				selected = " selected"
			}

			return template.HTML(fmt.Sprintf(`<option value="%s"%s>%s</option>`,
				html.EscapeString(fmt.Sprintf("%v", val)), selected, html.EscapeString(label)))
		},
		"radio": func(f *Field, val string) template.HTML {
			checked := ""
			if f.Flash() == val {
				checked = " checked"
			}
			return template.HTML(fmt.Sprintf(`<input type="radio" name="%s" value="%s"%s>`,
				html.EscapeString(f.Name), html.EscapeString(val), checked))
		},
		"checkbox": func(f *Field, val string) template.HTML {
			checked := ""
			if f.Flash() == val {
				checked = " checked"
			}
			return template.HTML(fmt.Sprintf(`<input type="checkbox" name="%s" value="%s"%s>`,
				html.EscapeString(f.Name), html.EscapeString(val), checked))
		},

		"pad": func(str string, width int) template.HTML {
			if len(str) >= width {
				return template.HTML(html.EscapeString(str))
			}
			return template.HTML(html.EscapeString(str) + strings.Repeat("&nbsp;", width-len(str)))
		},

		"errorClass": func(name string, viewArgs map[string]interface{}) template.HTML {
			errorMap, ok := viewArgs["errors"].(map[string]*ValidationError)
			if !ok || errorMap == nil {
				templateLog.Warn("errorClass: Called 'errorClass' without 'errors' in the view args.")
				return template.HTML("")
			}
			valError, ok := errorMap[name]
			if !ok || valError == nil {
				return template.HTML("")
			}
			return template.HTML(ErrorCSSClass)
		},

		"msg": func(viewArgs map[string]interface{}, message string, args ...interface{}) template.HTML {
			str, ok := viewArgs[CurrentLocaleViewArg].(string)
			if !ok {
				return ""
			}
			return template.HTML(MessageFunc(str, message, args...))
		},

		"nl2br": func(text string) template.HTML {
			return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1))
		},

		"raw": func(text string) template.HTML {
			return template.HTML(text)
		},

		"pluralize": func(items interface{}, pluralOverrides ...string) string {
			singular, plural := "", "s"
			if len(pluralOverrides) >= 1 {
				singular = pluralOverrides[0]
				if len(pluralOverrides) == 2 {
					plural = pluralOverrides[1]
				}
			}

			switch v := reflect.ValueOf(items); v.Kind() {
			case reflect.Int:
				if items.(int) != 1 {
					return plural
				}
			case reflect.Slice:
				if v.Len() != 1 {
					return plural
				}
			default:
				templateLog.Error("pluralize: unexpected type: ", "value", v)
			}
			return singular
		},

		"date": func(date time.Time) string {
			return date.Format(DateFormat)
		},
		"datetime": func(date time.Time) string {
			return date.Format(DateTimeFormat)
		},

		"session": func(key string, viewArgs map[string]interface{}) interface{} {
			if viewArgs != nil {
				if c, found := viewArgs["_controller"]; found {
					if v, err := c.(*Controller).Session.Get(key); err == nil {
						return v
					} else {
						templateLog.Errorf("template.session, key %s error %v", key, err)
					}
				} else {
					templateLog.Warnf("template.session, key %s requested without controller", key)
				}
			} else {
				templateLog.Warnf("template.session, key %s requested passing in view args", key)
			}
			return ""
		},

		"slug": Slug,
		"even": func(a int) bool { return (a % 2) == 0 },

		"timeago": TimeAgo,
		"i18ntemplate": func(args ...interface{}) (template.HTML, error) {
			templateName, lang := "", ""
			var viewArgs interface{}
			switch len(args) {
			case 0:
				templateLog.Error("i18ntemplate: No arguments passed to template call")
			case 1:

				templateName = args[0].(string)
			case 2:

				templateName = args[0].(string)
				viewArgs = args[1]

				if viewargsmap, ok := viewArgs.(map[string]interface{}); ok {
					lang, _ = viewargsmap[CurrentLocaleViewArg].(string)
				}
			default:

				templateName = args[0].(string)
				viewArgs = args[1]
				lang, _ = args[2].(string)
				if len(args) > 3 {
					templateLog.Error("i18ntemplate: Received more parameters then needed for", "template", templateName)
				}
			}

			var buf bytes.Buffer

			tmpl, err := MainTemplateLoader.TemplateLang(templateName, lang)
			if err == nil {
				err = tmpl.Render(&buf, viewArgs)
			} else {
				templateLog.Error("i18ntemplate: Failed to render i18ntemplate ", "name", templateName, "error", err)
			}
			return template.HTML(buf.String()), err
		},
	}
)
View Source
var WatchFilter = func(c *Controller, fc []Filter) {
	if MainWatcher != nil {
		err := MainWatcher.Notify()
		if err != nil {
			c.Result = c.RenderError(err)
			return
		}
	}
	fc[0](c, fc[1:])
}

Functions

func ActionInvoker

func ActionInvoker(c *Controller, _ []Filter)

func AddHTTPMux added in v0.21.0

func AddHTTPMux(path string, callback interface{})

Adds this routehandler to the route table. It will be called (if the path prefix matches) before the Revel mux, this can only be called after the ENGINE_BEFORE_INITIALIZED event

func AddInitEventHandler added in v0.16.0

func AddInitEventHandler(handler EventHandler)

Add event handler to listen for all system events

func Atob added in v0.14.0

func Atob(v string) bool

Atob converts string into boolean. It is in-case sensitive When converting to boolean, the following values are considered FALSE: - The "" (empty) string - The "false" string - The "f" string - The "off" string, - The string "0" & "0.0"

func BeforeAfterFilter added in v0.18.0

func BeforeAfterFilter(c *Controller, fc []Filter)

Autocalls any defined before and after methods on the target controller If either calls returns a value then the result is returned

func Bind

func Bind(params *Params, name string, typ reflect.Type) reflect.Value

Bind takes the name and type of the desired parameter and constructs it from one or more values from Params. Returns the zero value of the type upon any sort of failure.

func BindFile

func BindFile(fileHeader *multipart.FileHeader, typ reflect.Type) reflect.Value

func BindValue

func BindValue(val string, typ reflect.Type) reflect.Value

func CheckInit

func CheckInit()

CheckInit method checks `revel.Initialized` if not initialized it panics

func ClientIP added in v0.13.0

func ClientIP(r *Request) string

ClientIP method returns client IP address from HTTP request.

Note: Set property "app.behind.proxy" to true only if Revel is running behind proxy like nginx, haproxy, apache, etc. Otherwise you may get inaccurate Client IP address. Revel parses the IP address in the order of X-Forwarded-For, X-Real-IP.

By default revel will get http.Request's RemoteAddr

func CompressFilter

func CompressFilter(c *Controller, fc []Filter)

CompressFilter does compression of response body in gzip/deflate if `results.compressed=true` in the app.conf

func ContainsString

func ContainsString(list []string, target string) bool

func ContentTypeByFilename

func ContentTypeByFilename(filename string) string

ContentTypeByFilename returns a MIME content type based on the filename's extension. If no appropriate one is found, returns "application/octet-stream" by default. Additionally, specifies the charset as UTF-8 for text/* types.

func DirExists

func DirExists(filename string) bool

DirExists returns true if the given path exists and is a directory.

func EngineHandles added in v0.16.0

func EngineHandles(engine TemplateEngine, templateView *TemplateView) bool

func Equal

func Equal(a, b interface{}) bool

Equal is a helper for comparing value equality, following these rules:

- Values with equivalent types are compared with reflect.DeepEqual
- int, uint, and float values are compared without regard to the type width.
  for example, Equal(int32(5), int64(5)) == true
- strings and byte slices are converted to strings before comparison.
- else, return false.

func ExecuteTemplate

func ExecuteTemplate(tmpl ExecutableTemplate, data interface{}) string

ExecuteTemplate execute a template and returns the result as a string.

func FilterConfiguringFilter

func FilterConfiguringFilter(c *Controller, fc []Filter)

FilterConfiguringFilter is a filter stage that customizes the remaining filter chain for the action being invoked.

func FilterEq

func FilterEq(a, b Filter) bool

FilterEq returns true if the two filters reference the same filter.

func FindMethod

func FindMethod(recvType reflect.Type, funcVal reflect.Value) *reflect.Method

FindMethod returns the reflect.Method, given a Receiver type and Func value.

func FirstNonEmpty

func FirstNonEmpty(strs ...string) string

func FlashFilter

func FlashFilter(c *Controller, fc []Filter)

FlashFilter is a Revel Filter that retrieves and sets the flash cookie. Within Revel, it is available as a Flash attribute on Controller instances. The name of the Flash cookie is set as CookiePrefix + "_FLASH".

func HTTPMethodOverride added in v0.14.0

func HTTPMethodOverride(c *Controller, fc []Filter)

HTTPMethodOverride overrides allowed http methods via form or browser param

func HttpClientIP added in v0.21.0

func HttpClientIP(r *http.Request) string

ClientIP method returns client IP address from HTTP request.

Note: Set property "app.behind.proxy" to true only if Revel is running behind proxy like nginx, haproxy, apache, etc. Otherwise you may get inaccurate Client IP address. Revel parses the IP address in the order of X-Forwarded-For, X-Real-IP.

By default revel will get http.Request's RemoteAddr

func I18nFilter

func I18nFilter(c *Controller, fc []Filter)

func Init

func Init(inputmode, importPath, srcPath string)

Init initializes Revel -- it provides paths for getting around the app.

Params:

mode - the run mode, which determines which app.conf settings are used.
importPath - the Go import path of the application.
srcPath - the path to the source directory, containing Revel and the app.
  If not specified (""), then a functioning Go installation is required.

func InitServer added in v0.13.0

func InitServer()

InitServer initializes the server and returns the handler It can be used as an alternative entry-point if one needs the http handler to be exposed. E.g. to run on multiple addresses and ports or to set custom TLS options.

func InitServerEngine added in v0.18.0

func InitServerEngine(port int, serverEngine string)

Build an engine initialization object and start the engine

func InterceptFunc

func InterceptFunc(intc InterceptorFunc, when When, target interface{})

InterceptFunc installs a general interceptor. This can be applied to any Controller. It must have the signature of:

func example(c *revel.Controller) revel.Result

func InterceptMethod

func InterceptMethod(intc InterceptorMethod, when When)

InterceptMethod installs an interceptor method that applies to its own Controller.

func (c AppController) example() revel.Result
func (c *AppController) example() revel.Result

func InterceptorFilter

func InterceptorFilter(c *Controller, fc []Filter)

func LoadMimeConfig

func LoadMimeConfig()

LoadMimeConfig load mime-types.conf on init.

func Message

func Message(locale, message string, args ...interface{}) string

Message performs a message look-up for the given locale and message using the given arguments.

When either an unknown locale or message is detected, a specially formatted string is returned.

func MessageLanguages

func MessageLanguages() []string

MessageLanguages returns all currently loaded message languages.

func MustReadLines

func MustReadLines(filename string) []string

MustReadLines reads the lines of the given file. Panics in the case of error.

func OnAppStart

func OnAppStart(f func(), order ...int)

OnAppStart registers a function to be run at app startup.

The order you register the functions will be the order they are run. You can think of it as a FIFO queue. This process will happen after the config file is read and before the server is listening for connections.

Ideally, your application should have only one call to init() in the file init.go. The reason being that the call order of multiple init() functions in the same package is undefined. Inside of init() call revel.OnAppStart() for each function you wish to register.

Example:

// from: yourapp/app/controllers/somefile.go
func InitDB() {
    // do DB connection stuff here
}

func FillCache() {
    // fill a cache from DB
    // this depends on InitDB having been run
}

// from: yourapp/app/init.go
func init() {
    // set up filters...

    // register startup functions
    revel.OnAppStart(InitDB)
    revel.OnAppStart(FillCache)
}

This can be useful when you need to establish connections to databases or third-party services, setup app components, compile assets, or any thing you need to do between starting Revel and accepting connections.

func OnAppStop added in v0.21.0

func OnAppStop(f func(), order ...int)

Called to add a new stop hook

func PanicFilter

func PanicFilter(c *Controller, fc []Filter)

PanicFilter wraps the action invocation in a protective defer blanket that converts panics into 500 error pages.

func ParamsFilter

func ParamsFilter(c *Controller, fc []Filter)

func ParseKeyValueCookie

func ParseKeyValueCookie(val string, cb func(key, val string))

ParseKeyValueCookie takes the raw (escaped) cookie value and parses out key values.

func ParseParams

func ParseParams(params *Params, req *Request)

ParseParams parses the `http.Request` params into `revel.Controller.Params`

func ParseTemplateError added in v0.16.0

func ParseTemplateError(err error) (templateName string, line int, description string)

Parse the line, and description from an error message like: html/template:Application/Register.html:36: no such template "footer.html"

func ReadLines

func ReadLines(filename string) ([]string, error)

ReadLines reads the lines of the given file. Panics in the case of error.

func RegisterController

func RegisterController(c interface{}, methods []*MethodType)

RegisterController registers a Controller and its Methods with Revel.

func RegisterModuleInit added in v0.18.0

func RegisterModuleInit(callback ModuleCallbackInterface)

Called by a module init() function, caller will receive the *Module object created for that module This would be useful for assigning a logger for logging information in the module (since the module context would be correct)

func RegisterServerEngine added in v0.18.0

func RegisterServerEngine(name string, loader func() ServerEngine)

func RegisterSessionEngine added in v0.21.0

func RegisterSessionEngine(f func() SessionEngine, name string)

func RegisterTemplateLoader added in v0.16.0

func RegisterTemplateLoader(key string, loader func(loader *TemplateLoader) (TemplateEngine, error)) (err error)

Allow for templates to be registered during init but not initialized until application has been started

func ResolveContentType

func ResolveContentType(req *Request) string

ResolveContentType gets the content type. e.g. From "multipart/form-data; boundary=--" to "multipart/form-data" If none is specified, returns "text/html" by default.

func ResolveFormat

func ResolveFormat(req *Request) string

ResolveFormat maps the request's Accept MIME type declaration to a Request.Format attribute, specifically "html", "xml", "json", or "txt", returning a default of "html" when Accept header cannot be mapped to a value above.

func ResolveImportPath

func ResolveImportPath(importPath string) (string, error)

ResolveImportPath returns the filesystem path for the given import path. Returns an error if the import path could not be found.

func ReverseURL added in v0.14.0

func ReverseURL(args ...interface{}) (template.URL, error)

ReverseURL returns a url capable of invoking a given controller method: "Application.ShowApp 123" => "/app/123"

func RouterFilter

func RouterFilter(c *Controller, fc []Filter)

func Run

func Run(port int)

Run the server. This is called from the generated main file. If port is non-zero, use that. Else, read the port from app.conf.

func SessionFilter

func SessionFilter(c *Controller, fc []Filter)

func SetSecretKey added in v0.16.0

func SetSecretKey(newKey []byte) error

Set the secret key

func Sign

func Sign(message string) string

Sign a given string with the app-configured secret key. If no secret key is set, returns the empty string. Return the signature in base64 (URLEncoding).

func Slug

func Slug(text string) string

func TemplateOutputArgs added in v0.18.0

func TemplateOutputArgs(templatePath string, args map[string]interface{}) (data []byte, err error)

TemplateOutputArgs returns the result of the template rendered using the passed in arguments.

func TimeAgo added in v0.18.0

func TimeAgo(args ...interface{}) string

func ToBool added in v0.14.0

func ToBool(val interface{}) bool

ToBool method converts/assert value into true or false. Default is true. When converting to boolean, the following values are considered FALSE: - The integer value is 0 (zero) - The float value 0.0 (zero) - The complex value 0.0 (zero) - For string value, please refer `revel.Atob` method - An array, map, slice with zero elements - Boolean value returned as-is - "nil" value

func Unbind

func Unbind(output map[string]string, name string, val interface{})

func ValidationFilter

func ValidationFilter(c *Controller, fc []Filter)

ValidationFilter revel Filter function to be hooked into the filter chain.

func ValueBinder

func ValueBinder(f func(value string, typ reflect.Type) reflect.Value) func(*Params, string, reflect.Type) reflect.Value

ValueBinder is adapter for easily making one-key-value binders.

func Verify

func Verify(message, sig string) bool

Verify returns true if the given signature is correct for the given message. e.g. it matches what we generate with Sign()

func Walk added in v0.13.0

func Walk(root string, walkFn filepath.WalkFunc) error

Walk method extends filepath.Walk to also follow symlinks. Always returns the path of the file or directory.

Types

type AcceptLanguage

type AcceptLanguage struct {
	Language string
	Quality  float32
}

AcceptLanguage is a single language from the Accept-Language HTTP header.

type AcceptLanguages

type AcceptLanguages []AcceptLanguage

AcceptLanguages is collection of sortable AcceptLanguage instances.

func ResolveAcceptLanguage

func ResolveAcceptLanguage(req *Request) AcceptLanguages

ResolveAcceptLanguage returns a sorted list of Accept-Language header values.

The results are sorted using the quality defined in the header for each language range with the most qualified language range as the first element in the slice.

See the HTTP header fields specification (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4) for more details.

func (AcceptLanguages) Len

func (al AcceptLanguages) Len() int

func (AcceptLanguages) Less

func (al AcceptLanguages) Less(i, j int) bool

func (AcceptLanguages) String

func (al AcceptLanguages) String() string

func (AcceptLanguages) Swap

func (al AcceptLanguages) Swap(i, j int)

type ActionDefinition

type ActionDefinition struct {
	Host, Method, URL, Action string
	Star                      bool
	Args                      map[string]string
}

func (*ActionDefinition) String

func (a *ActionDefinition) String() string

type ActionPathData added in v0.17.1

type ActionPathData struct {
	Key                 string            // The unique key
	ControllerNamespace string            // The controller namespace
	ControllerName      string            // The controller name
	MethodName          string            // The method name
	Action              string            // The action
	ModuleSource        *Module           // The module
	Route               *Route            // The route
	FixedParamsByName   map[string]string // The fixed parameters
	TypeOfController    *ControllerType   // The controller type
}

type BinaryResult

type BinaryResult struct {
	Reader   io.Reader
	Name     string
	Length   int64
	Delivery ContentDisposition
	ModTime  time.Time
}

func (*BinaryResult) Apply

func (r *BinaryResult) Apply(req *Request, resp *Response)

type Binder

type Binder struct {
	// Bind takes the name and type of the desired parameter and constructs it
	// from one or more values from Params.
	//
	// Example
	//
	// Request:
	//   url?id=123&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=rob
	//
	// Action:
	//   Example.Action(id int, ol []int, ul []string, user User)
	//
	// Calls:
	//   Bind(params, "id", int): 123
	//   Bind(params, "ol", []int): {1, 2}
	//   Bind(params, "ul", []string): {"str", "array"}
	//   Bind(params, "user", User): User{Name:"rob"}
	//
	// Note that only exported struct fields may be bound.
	Bind func(params *Params, name string, typ reflect.Type) reflect.Value

	// Unbind serializes a given value to one or more URL parameters of the given
	// name.
	Unbind func(output map[string]string, name string, val interface{})
}

A Binder translates between string parameters and Go data structures.

type BufferedServerHeader added in v0.18.0

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

BufferedServerHeader will not send content out until the Released is called, from that point on it will act normally It implements all the ServerHeader

func NewBufferedServerHeader added in v0.18.0

func NewBufferedServerHeader(o ServerHeader) *BufferedServerHeader

Creates a new instance based on the ServerHeader

func (*BufferedServerHeader) Add added in v0.18.0

func (bsh *BufferedServerHeader) Add(key string, value string)

Add (append) to a key this value

func (*BufferedServerHeader) Del added in v0.18.0

func (bsh *BufferedServerHeader) Del(key string)

Delete this key

func (*BufferedServerHeader) Get added in v0.18.0

func (bsh *BufferedServerHeader) Get(key string) (value []string)

Get this key

func (*BufferedServerHeader) GetCookie added in v0.18.0

func (bsh *BufferedServerHeader) GetCookie(key string) (ServerCookie, error)

Returns a cookie

func (*BufferedServerHeader) GetKeys added in v0.21.0

func (bsh *BufferedServerHeader) GetKeys() (value []string)

Get all header keys

func (*BufferedServerHeader) Release added in v0.18.0

func (bsh *BufferedServerHeader) Release()

Release the header and push the results to the original

func (*BufferedServerHeader) Set added in v0.18.0

func (bsh *BufferedServerHeader) Set(key string, value string)

Sets (replace) the header key

func (*BufferedServerHeader) SetCookie added in v0.18.0

func (bsh *BufferedServerHeader) SetCookie(cookie string)

Sets the cookie

func (*BufferedServerHeader) SetStatus added in v0.18.0

func (bsh *BufferedServerHeader) SetStatus(statusCode int)

Set the status

type CompressResponseWriter

type CompressResponseWriter struct {
	Header             *BufferedServerHeader // The header
	ControllerResponse *Response             // The response
	OriginalWriter     io.Writer             // The writer
	// contains filtered or unexported fields
}

The compressed writer

func (*CompressResponseWriter) Close added in v0.10.0

func (c *CompressResponseWriter) Close() error

Close the writer

func (CompressResponseWriter) CloseNotify added in v0.10.0

func (c CompressResponseWriter) CloseNotify() <-chan bool

Called to notify the writer is closing

func (*CompressResponseWriter) Write

func (c *CompressResponseWriter) Write(b []byte) (int, error)

Write to the underling buffer

func (*CompressResponseWriter) WriteHeader

func (c *CompressResponseWriter) WriteHeader(status int)

Write the headers

type ContentDisposition

type ContentDisposition string
var (
	NoDisposition ContentDisposition = ""
	Attachment    ContentDisposition = "attachment"
	Inline        ContentDisposition = "inline"
)

type Controller

type Controller struct {
	Name          string          // The controller name, e.g. "Application"
	Type          *ControllerType // A description of the controller type.
	MethodName    string          // The method name, e.g. "Index"
	MethodType    *MethodType     // A description of the invoked action type.
	AppController interface{}     // The controller that was instantiated. embeds revel.Controller
	Action        string          // The fully qualified action name, e.g. "App.Index"
	ClientIP      string          // holds IP address of request came from

	Request  *Request
	Response *Response
	Result   Result

	Flash      Flash                  // User cookie, cleared after 1 request.
	Session    session.Session        // Session, stored using the session engine specified
	Params     *Params                // Parameters from URL and form (including multipart).
	Args       map[string]interface{} // Per-request scratch space.
	ViewArgs   map[string]interface{} // Variables passed to the template.
	Validation *Validation            // Data validation helpers
	Log        logger.MultiLogger     // Context Logger
}

Controller Revel's controller structure that gets embedded in user defined controllers

func NewController

func NewController(context ServerContext) *Controller

New controller, creates a new instance wrapping the request and response in it

func NewControllerEmpty added in v0.18.0

func NewControllerEmpty() *Controller

NewController returns new controller instance for Request and Response

func (*Controller) Destroy added in v0.18.0

func (c *Controller) Destroy()

func (*Controller) FlashParams

func (c *Controller) FlashParams()

FlashParams serializes the contents of Controller.Params to the Flash cookie.

func (*Controller) Forbidden

func (c *Controller) Forbidden(msg string, objs ...interface{}) Result

Forbidden returns an HTTP 403 Forbidden response whose body is the formatted string of msg and objs.

func (*Controller) Message

func (c *Controller) Message(message string, args ...interface{}) string

Message performs a lookup for the given message name using the given arguments using the current language defined for this controller.

The current language is set by the i18n plugin.

func (*Controller) NotFound

func (c *Controller) NotFound(msg string, objs ...interface{}) Result

NotFound returns an HTTP 404 Not Found response whose body is the formatted string of msg and objs.

func (*Controller) Redirect

func (c *Controller) Redirect(val interface{}, args ...interface{}) Result

Redirect to an action or to a URL.

c.Redirect(Controller.Action)
c.Redirect("/controller/action")
c.Redirect("/controller/%d/action", id)

func (*Controller) Render

func (c *Controller) Render(extraViewArgs ...interface{}) Result

Render a template corresponding to the calling Controller method. Arguments will be added to c.ViewArgs prior to rendering the template. They are keyed on their local identifier.

For example:

func (c Users) ShowUser(id int) revel.Result {
	 user := loadUser(id)
	 return c.Render(user)
}

This action will render views/Users/ShowUser.html, passing in an extra key-value "user": (User).

This is the slower magical version which uses the runtime to determine 1) Set c.ViewArgs to the arguments passed into this function 2) How to call the RenderTemplate by building the following line c.RenderTemplate(c.Name + "/" + c.MethodType.Name + "." + c.Request.Format)

If you want your code to run faster it is recommended you add the template values directly to the c.ViewArgs and call c.RenderTemplate directly

func (*Controller) RenderBinary

func (c *Controller) RenderBinary(memfile io.Reader, filename string, delivery ContentDisposition, modtime time.Time) Result

RenderBinary is like RenderFile() except that it instead of a file on disk, it renders data from memory (which could be a file that has not been written, the output from some function, or bytes streamed from somewhere else, as long it implements io.Reader). When called directly on something generated or streamed, modtime should mostly likely be time.Now().

func (*Controller) RenderError

func (c *Controller) RenderError(err error) Result

func (*Controller) RenderFile

func (c *Controller) RenderFile(file *os.File, delivery ContentDisposition) Result

RenderFile returns a file, either displayed inline or downloaded as an attachment. The name and size are taken from the file info.

func (*Controller) RenderFileName added in v0.19.0

func (c *Controller) RenderFileName(filename string, delivery ContentDisposition) Result

RenderFileName returns a file indicated by the path as provided via the filename. It can be either displayed inline or downloaded as an attachment. The name and size are taken from the file info.

func (*Controller) RenderHTML added in v0.14.0

func (c *Controller) RenderHTML(html string) Result

RenderHTML renders html in response

func (*Controller) RenderJSON added in v0.14.0

func (c *Controller) RenderJSON(o interface{}) Result

RenderJSON uses encoding/json.Marshal to return JSON to the client.

func (*Controller) RenderJSONP added in v0.14.0

func (c *Controller) RenderJSONP(callback string, o interface{}) Result

RenderJSONP renders JSONP result using encoding/json.Marshal

func (*Controller) RenderTemplate

func (c *Controller) RenderTemplate(templatePath string) Result

RenderTemplate method does less magical way to render a template. Renders the given template, using the current ViewArgs.

func (*Controller) RenderText

func (c *Controller) RenderText(text string, objs ...interface{}) Result

RenderText renders plaintext in response, printf style.

func (*Controller) RenderXML added in v0.14.0

func (c *Controller) RenderXML(o interface{}) Result

RenderXML uses encoding/xml.Marshal to return XML to the client.

func (*Controller) SetAction

func (c *Controller) SetAction(controllerName, methodName string) error

SetAction sets the action that is being invoked in the current request. It sets the following properties: Name, Action, Type, MethodType

func (*Controller) SetController added in v0.18.0

func (c *Controller) SetController(context ServerContext)

Sets the request and the response for the controller

func (*Controller) SetCookie

func (c *Controller) SetCookie(cookie *http.Cookie)

func (*Controller) SetTypeAction added in v0.17.1

func (c *Controller) SetTypeAction(controllerName, methodName string, typeOfController *ControllerType) error

SetAction sets the assigns the Controller type, sets the action and initializes the controller

func (*Controller) Stats added in v0.18.0

func (c *Controller) Stats() map[string]interface{}

This stats returns some interesting stats based on what is cached in memory and what is available directly

func (*Controller) TemplateOutput added in v0.18.0

func (c *Controller) TemplateOutput(templatePath string) (data []byte, err error)

TemplateOutput returns the result of the template rendered using the controllers ViewArgs.

func (*Controller) Todo

func (c *Controller) Todo() Result

Todo returns an HTTP 501 Not Implemented "todo" indicating that the action isn't done yet.

type ControllerFieldPath added in v0.18.0

type ControllerFieldPath struct {
	IsPointer      bool
	FieldIndexPath []int
	FunctionCall   reflect.Value
}

The controller field path provides the caller the ability to invoke the call directly

func (*ControllerFieldPath) Invoke added in v0.18.0

func (fieldPath *ControllerFieldPath) Invoke(value reflect.Value, input []reflect.Value) (result []reflect.Value)

type ControllerType

type ControllerType struct {
	Namespace         string  // The namespace of the controller
	ModuleSource      *Module // The module for the controller
	Type              reflect.Type
	Methods           []*MethodType
	ControllerIndexes [][]int // FieldByIndex to all embedded *Controllers
	ControllerEvents  *ControllerTypeEvents
}

Controller registry and types.

func AddControllerType added in v0.17.1

func AddControllerType(moduleSource *Module, controllerType reflect.Type, methods []*MethodType) (newControllerType *ControllerType)

Adds the controller to the controllers map using its namespace, also adds it to the module list of controllers. If the controller is in the main application it is added without its namespace as well.

func ControllerTypeByName added in v0.17.1

func ControllerTypeByName(controllerName string, moduleSource *Module) (c *ControllerType)

func (*ControllerType) Method

func (ct *ControllerType) Method(name string) *MethodType

Method searches for a given exported method (case insensitive)

func (*ControllerType) Name added in v0.17.1

func (ct *ControllerType) Name() string

The controller name with the namespace

func (*ControllerType) ShortName added in v0.17.1

func (ct *ControllerType) ShortName() string

The controller name without the namespace

type ControllerTypeEvents added in v0.18.0

type ControllerTypeEvents struct {
	Before, After, Finally, Panic []*ControllerFieldPath
}

func NewControllerTypeEvents added in v0.18.0

func NewControllerTypeEvents(c *ControllerType) (ce *ControllerTypeEvents)

type DiscerningListener

type DiscerningListener interface {
	Listener
	WatchDir(info os.FileInfo) bool
	WatchFile(basename string) bool
}

DiscerningListener allows the receiver to selectively watch files.

type Domain added in v0.17.1

type Domain struct {
	Regexp *regexp.Regexp
}

Requires a Domain string to be exactly

func ValidDomain added in v0.17.1

func ValidDomain() Domain

func (Domain) DefaultMessage added in v0.17.1

func (d Domain) DefaultMessage() string

func (Domain) IsSatisfied added in v0.17.1

func (d Domain) IsSatisfied(obj interface{}) bool

type Email

type Email struct {
	Match
}

func ValidEmail added in v0.9.1

func ValidEmail() Email

func (Email) DefaultMessage

func (e Email) DefaultMessage() string

type EngineInit added in v0.18.0

type EngineInit struct {
	Address,
	Network string // The network
	Port        int                 // The port
	HTTPMuxList ServerMuxList       // The HTTPMux
	Callback    func(ServerContext) // The ServerContext callback endpoint
}

The initialization structure passed into the engine

type Error

type Error struct {
	SourceType               string   // The type of source that failed to build.
	Title, Path, Description string   // Description of the error, as presented to the user.
	Line, Column             int      // Where the error was encountered.
	SourceLines              []string // The entire source file, split into lines.
	Stack                    string   // The raw stack trace string from debug.Stack().
	MetaError                string   // Error that occurred producing the error page.
	Link                     string   // A configurable link to wrap the error source in
}

Error description, used as an argument to the error template.

func NewErrorFromPanic

func NewErrorFromPanic(err interface{}) *Error

NewErrorFromPanic method finds the deepest stack from in user code and provide a code listing of that, on the line that eventually triggered the panic. Returns nil if no relevant stack frame can be found.

func (*Error) ContextSource

func (e *Error) ContextSource() []SourceLine

ContextSource method returns a snippet of the source around where the error occurred.

func (*Error) Error

func (e *Error) Error() string

Error method constructs a plaintext version of the error, taking account that fields are optionally set. Returns e.g. Compilation Error (in views/header.html:51): expected right delim in end; got "}"

func (e *Error) SetLink(errorLink string)

SetLink method prepares a link and assign to Error.Link attribute

type ErrorCoder added in v0.18.0

type ErrorCoder interface {
	HTTPCode() int
}

type ErrorResult

type ErrorResult struct {
	ViewArgs map[string]interface{}
	Error    error
}

ErrorResult structure used to handles all kinds of error codes (500, 404, ..). It renders the relevant error page (errors/CODE.format, e.g. errors/500.json). If RunMode is "dev", this results in a friendly error page.

func (ErrorResult) Apply

func (r ErrorResult) Apply(req *Request, resp *Response)

type Event added in v0.20.0

type Event int

The event type

const (
	// Event type when templates are going to be refreshed (receivers are registered template engines added to the template.engine conf option)
	TEMPLATE_REFRESH_REQUESTED Event = iota
	// Event type when templates are refreshed (receivers are registered template engines added to the template.engine conf option)
	TEMPLATE_REFRESH_COMPLETED

	// Event type before all module loads, events thrown to handlers added to AddInitEventHandler
	REVEL_BEFORE_MODULES_LOADED
	// Event type after all module loads, events thrown to handlers added to AddInitEventHandler
	REVEL_AFTER_MODULES_LOADED

	// Event type before server engine is initialized, receivers are active server engine and handlers added to AddInitEventHandler
	ENGINE_BEFORE_INITIALIZED
	// Event type before server engine is started, receivers are active server engine and handlers added to AddInitEventHandler
	ENGINE_STARTED

	// Event raised when the engine is told to shutdown
	ENGINE_SHUTDOWN_REQUEST

	// Event type after server engine is stopped, receivers are active server engine and handlers added to AddInitEventHandler
	ENGINE_SHUTDOWN

	// Called before routes are refreshed
	ROUTE_REFRESH_REQUESTED
	// Called after routes have been refreshed
	ROUTE_REFRESH_COMPLETED

	// Fired when a panic is caught during the startup process
	REVEL_FAILURE
)

type EventHandler added in v0.16.0

type EventHandler func(typeOf Event, value interface{}) (responseOf EventResponse)

The handler signature

type EventResponse added in v0.20.0

type EventResponse int

The event response

func RaiseEvent added in v0.20.0

func RaiseEvent(key Event, value interface{}) (response EventResponse)

Fires system events from revel

func StopServer added in v0.21.0

func StopServer(value interface{}) EventResponse

Called to stop the server

type ExecutableTemplate

type ExecutableTemplate interface {
	Execute(io.Writer, interface{}) error
}

ExecutableTemplate adds some more methods to the default Template.

type Field

type Field struct {
	Name  string
	Error *ValidationError
	// contains filtered or unexported fields
}

Field represents a data field that may be collected in a web form.

func NewField

func NewField(name string, viewArgs map[string]interface{}) *Field

func (*Field) ErrorClass

func (f *Field) ErrorClass() string

ErrorClass returns ErrorCSSClass if this field has a validation error, else empty string.

func (*Field) Flash

func (f *Field) Flash() string

Flash returns the flashed value of this Field.

func (*Field) FlashArray

func (f *Field) FlashArray() []string

FlashArray returns the flashed value of this Field as a list split on comma.

func (*Field) ID added in v0.14.0

func (f *Field) ID() string

ID returns an identifier suitable for use as an HTML id.

func (*Field) Options added in v0.19.0

func (f *Field) Options() []string

Options returns the option list of this Field.

func (*Field) ShortName added in v0.18.0

func (f *Field) ShortName() string

Get the short name and translate it

func (*Field) Translate added in v0.18.0

func (f *Field) Translate(text string, args ...interface{}) string

Translate the text

func (*Field) Value

func (f *Field) Value() interface{}

Value returns the current value of this Field.

type FilePath added in v0.17.1

type FilePath struct {
	Mode int
}

Requires an string to be sanitary file path

func ValidFilePath added in v0.17.1

func ValidFilePath(m int) FilePath

func (FilePath) DefaultMessage added in v0.17.1

func (f FilePath) DefaultMessage() string

func (FilePath) IsSatisfied added in v0.17.1

func (f FilePath) IsSatisfied(obj interface{}) bool

type Filter

type Filter func(c *Controller, filterChain []Filter)

Filter type definition for Revel's filter

type FilterConfigurator

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

FilterConfigurator allows the developer configure the filter chain on a per-controller or per-action basis. The filter configuration is applied by the FilterConfiguringFilter, which is itself a filter stage. For example,

Assuming:

Filters = []Filter{
  RouterFilter,
  FilterConfiguringFilter,
  SessionFilter,
  ActionInvoker,
}

Add:

FilterAction(App.Action).
  Add(OtherFilter)

=> RouterFilter, FilterConfiguringFilter, SessionFilter, OtherFilter, ActionInvoker

Remove:

FilterAction(App.Action).
  Remove(SessionFilter)

=> RouterFilter, FilterConfiguringFilter, OtherFilter, ActionInvoker

Insert:

FilterAction(App.Action).
  Insert(OtherFilter, revel.BEFORE, SessionFilter)

=> RouterFilter, FilterConfiguringFilter, OtherFilter, SessionFilter, ActionInvoker

Filter modifications may be combined between Controller and Action. For example:

 FilterController(App{}).
   Add(Filter1)
 FilterAction(App.Action).
   Add(Filter2)

.. would result in App.Action being filtered by both Filter1 and Filter2.

Note: the last filter stage is not subject to the configurator. In particular, Add() adds a filter to the second-to-last place.

func FilterAction

func FilterAction(methodRef interface{}) FilterConfigurator

FilterAction returns a configurator for the filters applied to the given controller method. For example:

FilterAction(MyController.MyAction)

func FilterController

func FilterController(controllerInstance interface{}) FilterConfigurator

FilterController returns a configurator for the filters applied to all actions on the given controller instance. For example:

FilterController(MyController{})

func (FilterConfigurator) Add

Add the given filter in the second-to-last position in the filter chain. (Second-to-last so that it is before ActionInvoker)

func (FilterConfigurator) Insert

func (conf FilterConfigurator) Insert(insert Filter, where When, target Filter) FilterConfigurator

Insert a filter into the filter chain before or after another. This may be called with the BEFORE or AFTER constants, for example:

revel.FilterAction(App.Index).
  Insert(MyFilter, revel.BEFORE, revel.ActionInvoker).
  Insert(MyFilter2, revel.AFTER, revel.PanicFilter)

func (FilterConfigurator) Remove

func (conf FilterConfigurator) Remove(target Filter) FilterConfigurator

Remove a filter from the filter chain.

type Flash

type Flash struct {
	// `Data` is the input which is read in `restoreFlash`, `Out` is the output which is set in a FLASH cookie at the end of the `FlashFilter()`
	Data, Out map[string]string
}

Flash represents a cookie that is overwritten on each request. It allows data to be stored across one page at a time. This is commonly used to implement success or error messages. E.g. the Post/Redirect/Get pattern: http://en.wikipedia.org/wiki/Post/Redirect/Get

func (Flash) Error

func (f Flash) Error(msg string, args ...interface{})

Error serializes the given msg and args to an "error" key within the Flash cookie.

func (Flash) Success

func (f Flash) Success(msg string, args ...interface{})

Success serializes the given msg and args to a "success" key within the Flash cookie.

type GoContext added in v0.18.0

type GoContext struct {
	Request   *GoRequest   // The request
	Response  *GoResponse  // The response
	WebSocket *GoWebSocket // The websocket
}

The go context

func NewGoContext added in v0.18.0

func NewGoContext(instance *GoHttpServer) *GoContext

Create a new go context

func (*GoContext) Destroy added in v0.18.0

func (c *GoContext) Destroy()

Destroy the context

func (*GoContext) GetRequest added in v0.18.0

func (c *GoContext) GetRequest() ServerRequest

get the request

func (*GoContext) GetResponse added in v0.18.0

func (c *GoContext) GetResponse() ServerResponse

Get the response

type GoCookie added in v0.18.0

type GoCookie http.Cookie

The cookie

func (GoCookie) GetValue added in v0.18.0

func (r GoCookie) GetValue() string

Return cookies value

type GoEngine added in v0.16.0

type GoEngine struct {

	// True if map is case insensitive
	CaseInsensitive bool
	// contains filtered or unexported fields
}

The main template engine for Go

func (*GoEngine) ConvertPath added in v0.16.0

func (i *GoEngine) ConvertPath(path string) string

Convert the path to lower case if needed

func (*GoEngine) Event added in v0.16.0

func (engine *GoEngine) Event(action Event, i interface{})

An event listener to listen for Revel INIT events

func (*GoEngine) Handles added in v0.16.0

func (i *GoEngine) Handles(templateView *TemplateView) bool

Returns true if this engine can handle the response

func (*GoEngine) Lookup added in v0.16.0

func (engine *GoEngine) Lookup(templateName string) Template

Lookups the template name, to see if it is contained in this engine

func (*GoEngine) Name added in v0.16.0

func (engine *GoEngine) Name() string

Return the engine name

func (*GoEngine) ParseAndAdd added in v0.16.0

func (engine *GoEngine) ParseAndAdd(baseTemplate *TemplateView) error

Parses the template vide and adds it to the template set

type GoHeader added in v0.18.0

type GoHeader struct {
	Source interface{} // The source
	// contains filtered or unexported fields
}

The go header

func (*GoHeader) Add added in v0.18.0

func (r *GoHeader) Add(key string, value string)

Adds the header key

func (*GoHeader) Del added in v0.18.0

func (r *GoHeader) Del(key string)

Deletes the header key

func (*GoHeader) Get added in v0.18.0

func (r *GoHeader) Get(key string) (value []string)

Gets the header key

func (*GoHeader) GetCookie added in v0.18.0

func (r *GoHeader) GetCookie(key string) (value ServerCookie, err error)

Gets the cookie

func (*GoHeader) GetKeys added in v0.21.0

func (r *GoHeader) GetKeys() (value []string)

Returns list of header keys

func (*GoHeader) Set added in v0.18.0

func (r *GoHeader) Set(key string, value string)

Sets (replaces) header key

func (*GoHeader) SetCookie added in v0.18.0

func (r *GoHeader) SetCookie(cookie string)

Sets the cookie

func (*GoHeader) SetStatus added in v0.18.0

func (r *GoHeader) SetStatus(statusCode int)

Sets the status of the header

type GoHttpServer added in v0.18.0

type GoHttpServer struct {
	Server           *http.Server // The server instance
	ServerInit       *EngineInit  // The server engine initialization
	MaxMultipartSize int64        // The largest size of file to accept

	HttpMuxList ServerMuxList
	HasAppMux   bool
	// contains filtered or unexported fields
}

The Go HTTP server

func (*GoHttpServer) Engine added in v0.18.0

func (g *GoHttpServer) Engine() interface{}

Return the engine instance

func (*GoHttpServer) Event added in v0.18.0

func (g *GoHttpServer) Event(event Event, args interface{}) (r EventResponse)

Handles an event from Revel

func (*GoHttpServer) Handle added in v0.18.0

func (g *GoHttpServer) Handle(w http.ResponseWriter, r *http.Request)

Handle the request and response for the server

func (*GoHttpServer) Init added in v0.18.0

func (g *GoHttpServer) Init(init *EngineInit)

Called to initialize the server with this EngineInit

func (*GoHttpServer) Name added in v0.18.0

func (g *GoHttpServer) Name() string

Returns the name of this engine

func (*GoHttpServer) Start added in v0.18.0

func (g *GoHttpServer) Start()

Handler is assigned in the Init

func (*GoHttpServer) Stats added in v0.18.0

func (g *GoHttpServer) Stats() map[string]interface{}

Returns stats for this engine

type GoMultipartForm added in v0.18.0

type GoMultipartForm struct {
	Form *multipart.Form // The form
}

The multipart form

func (*GoMultipartForm) GetFiles added in v0.18.0

func (f *GoMultipartForm) GetFiles() map[string][]*multipart.FileHeader

Return files from the form

func (*GoMultipartForm) GetValues added in v0.18.0

func (f *GoMultipartForm) GetValues() url.Values

Return values from the form

func (*GoMultipartForm) RemoveAll added in v0.18.0

func (f *GoMultipartForm) RemoveAll() error

Remove all values from the form freeing memory

type GoRequest added in v0.18.0

type GoRequest struct {
	Original        *http.Request    // The original
	FormParsed      bool             // True if form parsed
	MultiFormParsed bool             // True if multipart form parsed
	WebSocket       *websocket.Conn  // The websocket
	ParsedForm      *GoMultipartForm // The parsed form data
	Goheader        *GoHeader        // The header
	Engine          *GoHttpServer    // THe server
}

The go request

func (*GoRequest) Destroy added in v0.18.0

func (r *GoRequest) Destroy()

Destroy the request

func (*GoRequest) Get added in v0.18.0

func (r *GoRequest) Get(key int) (value interface{}, err error)

Communicate with the server engine to exchange data

func (*GoRequest) GetForm added in v0.18.0

func (r *GoRequest) GetForm() (url.Values, error)

Returns the form

func (*GoRequest) GetHeader added in v0.18.0

func (r *GoRequest) GetHeader() ServerHeader

Returns the header

func (*GoRequest) GetMultipartForm added in v0.18.0

func (r *GoRequest) GetMultipartForm() (ServerMultipartForm, error)

Returns the form

func (*GoRequest) GetRaw added in v0.18.0

func (r *GoRequest) GetRaw() interface{}

Returns the raw value

func (*GoRequest) Set added in v0.18.0

func (r *GoRequest) Set(key int, value interface{}) bool

Sets the request key with value

func (*GoRequest) SetRequest added in v0.18.0

func (r *GoRequest) SetRequest(req *http.Request)

Sets the request

type GoResponse added in v0.18.0

type GoResponse struct {
	Original http.ResponseWriter // The original writer
	Goheader *GoHeader           // The header
	Writer   io.Writer           // The writer
	Request  *GoRequest          // The request
	Engine   *GoHttpServer       // The engine
}

The response

func (*GoResponse) Destroy added in v0.18.0

func (r *GoResponse) Destroy()

Frees response

func (*GoResponse) Get added in v0.18.0

func (r *GoResponse) Get(key int) (value interface{}, err error)

Gets the key from the response

func (*GoResponse) GetRaw added in v0.18.0

func (r *GoResponse) GetRaw() interface{}

Gets the original response

func (*GoResponse) Header added in v0.18.0

func (r *GoResponse) Header() ServerHeader

Sets the header

func (*GoResponse) Set added in v0.18.0

func (r *GoResponse) Set(key int, value interface{}) (set bool)

Sets the key with the value

func (*GoResponse) SetResponse added in v0.18.0

func (r *GoResponse) SetResponse(w http.ResponseWriter)

Sets the response

func (*GoResponse) SetWriter added in v0.18.0

func (r *GoResponse) SetWriter(writer io.Writer)

Sets the writer

func (*GoResponse) WriteStream added in v0.18.0

func (r *GoResponse) WriteStream(name string, contentlen int64, modtime time.Time, reader io.Reader) error

Write output to stream

type GoTemplate

type GoTemplate struct {
	*template.Template

	*TemplateView
	// contains filtered or unexported fields
}

Adapter for Go Templates.

func (GoTemplate) Render

func (gotmpl GoTemplate) Render(wr io.Writer, arg interface{}) error

return a 'revel.Template' from Go's template.

type GoWebSocket added in v0.18.0

type GoWebSocket struct {
	Conn       *websocket.Conn // The connection
	GoResponse                 // The response
}

The websocket

func (*GoWebSocket) MessageReceive added in v0.20.0

func (g *GoWebSocket) MessageReceive(v interface{}) error

*

* Message receive

func (*GoWebSocket) MessageReceiveJSON added in v0.18.0

func (g *GoWebSocket) MessageReceiveJSON(v interface{}) error

*

* Message receive JSON

func (*GoWebSocket) MessageSend added in v0.20.0

func (g *GoWebSocket) MessageSend(v interface{}) error

*

* Message Send

func (*GoWebSocket) MessageSendJSON added in v0.18.0

func (g *GoWebSocket) MessageSendJSON(v interface{}) error

*

* Message send JSON

type IPAddr added in v0.17.1

type IPAddr struct {
	Vaildtypes []int
}

Requires a string(IP Address) to be within IP Pattern type inclusive.

func ValidIPAddr added in v0.17.1

func ValidIPAddr(cktypes ...int) IPAddr

Requires an IP Address string to be exactly a given validation type (IPv4, IPv6, IPv4MappedIPv6, IPv4CIDR, IPv6CIDR, IPv4MappedIPv6CIDR OR IPAny)

func (IPAddr) DefaultMessage added in v0.17.1

func (i IPAddr) DefaultMessage() string

func (IPAddr) IsSatisfied added in v0.17.1

func (i IPAddr) IsSatisfied(obj interface{}) bool

type InterceptTarget

type InterceptTarget int
const (
	AllControllers InterceptTarget = iota
)

type Interception

type Interception struct {
	When When
	// contains filtered or unexported fields
}

func (Interception) Invoke

func (i Interception) Invoke(val reflect.Value, target *reflect.Value) reflect.Value

Invoke performs the given interception. val is a pointer to the App Controller.

type InterceptorFunc

type InterceptorFunc func(*Controller) Result

An InterceptorFunc is functionality invoked by the framework BEFORE or AFTER an action.

An interceptor may optionally return a Result (instead of nil). Depending on when the interceptor was invoked, the response is different: 1. BEFORE: No further interceptors are invoked, and neither is the action. 2. AFTER: Further interceptors are still run. In all cases, any returned Result will take the place of any existing Result.

In the BEFORE case, that returned Result is guaranteed to be final, while in the AFTER case it is possible that a further interceptor could emit its own Result.

Interceptors are called in the order that they are added.

***

Two types of interceptors are provided: Funcs and Methods

Func Interceptors may apply to any / all Controllers.

func example(*revel.Controller) revel.Result

Method Interceptors are provided so that properties can be set on application controllers.

func (c AppController) example() revel.Result
func (c *AppController) example() revel.Result

type InterceptorMethod

type InterceptorMethod interface{}

type Length

type Length struct {
	N int
}

Length requires an array or string to be exactly a given length.

func ValidLength

func ValidLength(n int) Length

func (Length) DefaultMessage

func (s Length) DefaultMessage() string

func (Length) IsSatisfied

func (s Length) IsSatisfied(obj interface{}) bool

type Listener

type Listener interface {
	// Refresh is invoked by the watcher on relevant filesystem events.
	// If the listener returns an error, it is served to the user on the current request.
	Refresh() *Error
}

Listener is an interface for receivers of filesystem events.

type MacAddr added in v0.17.1

type MacAddr struct{}

Requires a MAC Address string to be exactly

func ValidMacAddr added in v0.17.1

func ValidMacAddr() MacAddr

func (MacAddr) DefaultMessage added in v0.17.1

func (m MacAddr) DefaultMessage() string

func (MacAddr) IsSatisfied added in v0.17.1

func (m MacAddr) IsSatisfied(obj interface{}) bool

type Match

type Match struct {
	Regexp *regexp.Regexp
}

Match requires a string to match a given regex.

func ValidMatch

func ValidMatch(regex *regexp.Regexp) Match

func (Match) DefaultMessage

func (m Match) DefaultMessage() string

func (Match) IsSatisfied

func (m Match) IsSatisfied(obj interface{}) bool

type Max

type Max struct {
	Max float64
}

func ValidMax

func ValidMax(max int) Max

func ValidMaxFloat added in v0.18.0

func ValidMaxFloat(max float64) Max

func (Max) DefaultMessage

func (m Max) DefaultMessage() string

func (Max) IsSatisfied

func (m Max) IsSatisfied(obj interface{}) bool

type MaxSize

type MaxSize struct {
	Max int
}

MaxSize requires an array or string to be at most a given length.

func ValidMaxSize

func ValidMaxSize(max int) MaxSize

func (MaxSize) DefaultMessage

func (m MaxSize) DefaultMessage() string

func (MaxSize) IsSatisfied

func (m MaxSize) IsSatisfied(obj interface{}) bool

type MethodArg

type MethodArg struct {
	Name string
	Type reflect.Type
}

type MethodType

type MethodType struct {
	Name           string
	Args           []*MethodArg
	RenderArgNames map[int][]string

	Index int
	// contains filtered or unexported fields
}

type Min

type Min struct {
	Min float64
}

func ValidMin

func ValidMin(min int) Min

func ValidMinFloat added in v0.18.0

func ValidMinFloat(min float64) Min

func (Min) DefaultMessage

func (m Min) DefaultMessage() string

func (Min) IsSatisfied

func (m Min) IsSatisfied(obj interface{}) bool

type MinSize

type MinSize struct {
	Min int
}

MinSize requires an array or string to be at least a given length.

func ValidMinSize

func ValidMinSize(min int) MinSize

func (MinSize) DefaultMessage

func (m MinSize) DefaultMessage() string

func (MinSize) IsSatisfied

func (m MinSize) IsSatisfied(obj interface{}) bool

type Module

type Module struct {
	Name, ImportPath, Path string
	ControllerTypeList     []*ControllerType
	Log                    logger.MultiLogger
	// contains filtered or unexported fields
}

Module specific functions

func ModuleByName

func ModuleByName(name string) (*Module, bool)

ModuleByName returns the module of the given name, if loaded, case insensitive.

func ModuleFromPath added in v0.17.1

func ModuleFromPath(packagePath string, addGopathToPath bool) (module *Module)

Based on the full path given return the relevant module Only to be used on initialization

func (*Module) AddController added in v0.17.1

func (m *Module) AddController(ct *ControllerType)

Adds the controller type to this module

func (*Module) ControllerByName added in v0.17.1

func (m *Module) ControllerByName(name, action string) (ctype *ControllerType)

Returns the named controller and action that is in this module

func (*Module) Namespace added in v0.17.1

func (m *Module) Namespace() (namespace string)

Returns the namespace for the module in the format `module_name|`

type ModuleCallbackInterface added in v0.18.0

type ModuleCallbackInterface func(*Module)

Modules can be called back after they are loaded in revel by using this interface.

type MultipartForm added in v0.18.0

type MultipartForm struct {
	File  map[string][]*multipart.FileHeader
	Value url.Values
	// contains filtered or unexported fields
}

Deprecated for backwards compatibility only

type OutResponse added in v0.18.0

type OutResponse struct {
	Server ServerResponse // The server response
	// contains filtered or unexported fields
}

The output response

func (*OutResponse) Destroy added in v0.18.0

func (o *OutResponse) Destroy()

Destroy the output response

func (*OutResponse) Header added in v0.18.0

func (o *OutResponse) Header() *RevelHeader

Return the header

func (*OutResponse) Write added in v0.18.0

func (o *OutResponse) Write(data []byte) (int, error)

Write the header out

type Params

type Params struct {
	url.Values // A unified view of all the individual param maps below.

	// Set by the router
	Fixed url.Values // Fixed parameters from the route, e.g. App.Action("fixed param")
	Route url.Values // Parameters extracted from the route,  e.g. /customers/{id}

	// Set by the ParamsFilter
	Query url.Values // Parameters from the query string, e.g. /index?limit=10
	Form  url.Values // Parameters from the request body.

	Files map[string][]*multipart.FileHeader // Files uploaded in a multipart form

	JSON []byte // JSON data from request body
	// contains filtered or unexported fields
}

Params provides a unified view of the request params. Includes: - URL query string - Form values - File uploads

Warning: param maps other than Values may be nil if there were none.

func (*Params) Bind

func (p *Params) Bind(dest interface{}, name string)

Bind looks for the named parameter, converts it to the requested type, and writes it into "dest", which must be settable. If the value can not be parsed, "dest" is set to the zero value.

func (*Params) BindJSON added in v0.16.0

func (p *Params) BindJSON(dest interface{}) error

Bind binds the JSON data to the dest.

type PlaintextErrorResult

type PlaintextErrorResult struct {
	Error error
}

func (PlaintextErrorResult) Apply

func (r PlaintextErrorResult) Apply(req *Request, resp *Response)

Apply method is used when the template loader or error template is not available.

type PureText added in v0.17.1

type PureText struct {
	Mode int
}

Requires a string to be without invisible characters

func ValidPureText added in v0.17.1

func ValidPureText(m int) PureText

func (PureText) DefaultMessage added in v0.17.1

func (p PureText) DefaultMessage() string

func (PureText) IsSatisfied added in v0.17.1

func (p PureText) IsSatisfied(obj interface{}) bool

type Range

type Range struct {
	Min
	Max
}

Range requires an integer to be within Min, Max inclusive.

func ValidRange

func ValidRange(min, max int) Range

func ValidRangeFloat added in v0.18.0

func ValidRangeFloat(min, max float64) Range

func (Range) DefaultMessage

func (r Range) DefaultMessage() string

func (Range) IsSatisfied

func (r Range) IsSatisfied(obj interface{}) bool

type RedirectToActionResult

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

func (*RedirectToActionResult) Apply

func (r *RedirectToActionResult) Apply(req *Request, resp *Response)

type RedirectToURLResult added in v0.14.0

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

func (*RedirectToURLResult) Apply added in v0.14.0

func (r *RedirectToURLResult) Apply(req *Request, resp *Response)

type RenderHTMLResult added in v0.14.0

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

func (RenderHTMLResult) Apply added in v0.14.0

func (r RenderHTMLResult) Apply(req *Request, resp *Response)

type RenderJSONResult added in v0.14.0

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

func (RenderJSONResult) Apply added in v0.14.0

func (r RenderJSONResult) Apply(req *Request, resp *Response)

type RenderTemplateResult

type RenderTemplateResult struct {
	Template Template
	ViewArgs map[string]interface{}
}

RenderTemplateResult action methods returns this result to request a template be rendered.

func (*RenderTemplateResult) Apply

func (r *RenderTemplateResult) Apply(req *Request, resp *Response)

func (*RenderTemplateResult) ToBytes added in v0.18.0

func (r *RenderTemplateResult) ToBytes() (b *bytes.Buffer, err error)

Return a byte array and or an error object if the template failed to render

type RenderTextResult

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

func (RenderTextResult) Apply

func (r RenderTextResult) Apply(req *Request, resp *Response)

type RenderXMLResult added in v0.14.0

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

func (RenderXMLResult) Apply added in v0.14.0

func (r RenderXMLResult) Apply(req *Request, resp *Response)

type Request

type Request struct {
	In              ServerRequest   // The server request
	Header          *RevelHeader    // The revel header
	ContentType     string          // The content type
	Format          string          // The output format "html", "xml", "json", or "txt"
	AcceptLanguages AcceptLanguages // The languages to accept
	Locale          string          // THe locale
	WebSocket       ServerWebSocket // The websocket
	Method          string          // The method
	RemoteAddr      string          // The remote address
	Host            string          // The host
	// URL request path from the server (built)
	URL *url.URL // The url
	// DEPRECATED use GetForm()
	Form url.Values // The Form
	// DEPRECATED use GetMultipartForm()
	MultipartForm *MultipartForm // The multipart form
	// contains filtered or unexported fields
}

Request is Revel's HTTP request object structure

func NewRequest

func NewRequest(r ServerRequest) *Request

NewRequest returns a Revel's HTTP request instance with given HTTP instance

func (*Request) Args added in v0.20.0

func (req *Request) Args() map[string]interface{}

Return the args for the controller

func (*Request) Context added in v0.18.0

func (req *Request) Context() (c context.Context)

Fetch the context

func (*Request) Cookie added in v0.18.0

func (req *Request) Cookie(key string) (ServerCookie, error)

Returns a cookie

func (*Request) Destroy added in v0.18.0

func (req *Request) Destroy()

Destroy the request

func (*Request) FormValue added in v0.18.0

func (req *Request) FormValue(key string) (value string)

Deprecated use controller.Params.Get()

func (*Request) GetBody added in v0.18.0

func (req *Request) GetBody() (body io.Reader)

Fetch the body

func (*Request) GetForm added in v0.18.0

func (req *Request) GetForm() (url.Values, error)

func (*Request) GetHttpHeader added in v0.18.0

func (req *Request) GetHttpHeader(key string) string

Return the httpheader for the key

func (*Request) GetMultipartForm added in v0.18.0

func (req *Request) GetMultipartForm() (ServerMultipartForm, error)

Return a multipart form

func (*Request) GetPath added in v0.18.0

func (req *Request) GetPath() (path string)

Fetch the path

func (*Request) GetQuery added in v0.18.0

func (req *Request) GetQuery() (v url.Values)

Fetch the query

func (*Request) GetRequestURI added in v0.18.0

func (req *Request) GetRequestURI() string

Fetch the requested URI

func (*Request) GetValue added in v0.18.0

func (r *Request) GetValue(key int) (value interface{})

Return the value from the server

func (*Request) MultipartReader added in v0.18.0

func (req *Request) MultipartReader() (*multipart.Reader, error)

func (*Request) ParseForm added in v0.18.0

func (req *Request) ParseForm() (e error)

Deprecated use GetForm() instead

func (*Request) ParseMultipartForm added in v0.18.0

func (req *Request) ParseMultipartForm(_ int64) (e error)

Deprecated use GetMultipartForm() instead

func (*Request) PostFormValue added in v0.18.0

func (req *Request) PostFormValue(key string) (value string)

Deprecated use controller.Params.Form[Key]

func (*Request) Referer added in v0.18.0

func (req *Request) Referer() string

Referer returns the client's Referer header string.

func (*Request) SetRequest added in v0.18.0

func (req *Request) SetRequest(r ServerRequest)

func (*Request) UserAgent added in v0.18.0

func (r *Request) UserAgent() string

UserAgent returns the client's User-Agent header string.

type Required

type Required struct{}

func ValidRequired

func ValidRequired() Required

func (Required) DefaultMessage

func (r Required) DefaultMessage() string

func (Required) IsSatisfied

func (r Required) IsSatisfied(obj interface{}) bool

type Response

type Response struct {
	Status      int
	ContentType string
	Out         OutResponse
	// contains filtered or unexported fields
}

Response is Revel's HTTP response object structure

func NewResponse

func NewResponse(w ServerResponse) (r *Response)

NewResponse wraps ServerResponse inside a Revel's Response and returns it

func (*Response) Destroy added in v0.18.0

func (resp *Response) Destroy()

Destroy the Response

func (*Response) GetStreamWriter added in v0.18.0

func (resp *Response) GetStreamWriter() (writer StreamWriter)

Passes full control to the response to the caller - terminates any initial writes

func (*Response) GetWriter added in v0.18.0

func (resp *Response) GetWriter() (writer io.Writer)

Return the writer

func (*Response) SetResponse added in v0.18.0

func (resp *Response) SetResponse(r ServerResponse)

Set the server response

func (*Response) SetStatus added in v0.18.0

func (resp *Response) SetStatus(statusCode int)

func (*Response) SetWriter added in v0.18.0

func (resp *Response) SetWriter(writer io.Writer) bool

Replace the writer

func (*Response) WriteHeader

func (resp *Response) WriteHeader(defaultStatusCode int, defaultContentType string)

WriteHeader writes the header (for now, just the status code). The status may be set directly by the application (c.Response.Status = 501). If it isn't, then fall back to the provided status code.

type Result

type Result interface {
	Apply(req *Request, resp *Response)
}

type RevelHeader added in v0.18.0

type RevelHeader struct {
	Server ServerHeader // The server
}

The header defined in Revel

func (*RevelHeader) Add added in v0.18.0

func (h *RevelHeader) Add(key, value string)

Add a key to the header

func (*RevelHeader) Destroy added in v0.18.0

func (h *RevelHeader) Destroy()

Destroy the RevelHeader

func (*RevelHeader) Get added in v0.18.0

func (h *RevelHeader) Get(key string) (value string)

Get a key from the header

func (*RevelHeader) GetAll added in v0.18.0

func (h *RevelHeader) GetAll(key string) (values []string)

GetAll returns []string of items (the header split by a comma)

func (*RevelHeader) Set added in v0.18.0

func (h *RevelHeader) Set(key, value string)

Set a value in the header

func (*RevelHeader) SetCookie added in v0.18.0

func (h *RevelHeader) SetCookie(cookie string)

Set a cookie in the header

func (*RevelHeader) SetStatus added in v0.18.0

func (h *RevelHeader) SetStatus(status int)

Set the status for the header

type RevelHook added in v0.21.0

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

The startup hooks structure

type RevelHooks added in v0.21.0

type RevelHooks []RevelHook

The list of startup hooks

func (RevelHooks) Add added in v0.21.0

func (r RevelHooks) Add(fn func(), order ...int) RevelHooks

Adds a new function hook, using the order

func (RevelHooks) Len added in v0.21.0

func (slice RevelHooks) Len() int

Sorting function

func (RevelHooks) Less added in v0.21.0

func (slice RevelHooks) Less(i, j int) bool

Sorting function

func (RevelHooks) Run added in v0.21.0

func (r RevelHooks) Run()

Called to run the hooks

func (RevelHooks) Swap added in v0.21.0

func (slice RevelHooks) Swap(i, j int)

Sorting function

type Route

type Route struct {
	ModuleSource        *Module         // Module name of route
	Method              string          // e.g. GET
	Path                string          // e.g. /app/:id
	Action              string          // e.g. "Application.ShowApp", "404"
	ControllerNamespace string          // e.g. "testmodule.",
	ControllerName      string          // e.g. "Application", ""
	MethodName          string          // e.g. "ShowApp", ""
	FixedParams         []string        // e.g. "arg1","arg2","arg3" (CSV formatting)
	TreePath            string          // e.g. "/GET/app/:id"
	TypeOfController    *ControllerType // The controller type (if route is not wild carded)
	// contains filtered or unexported fields
}

func NewRoute

func NewRoute(moduleSource *Module, method, path, action, fixedArgs, routesPath string, line int) (r *Route)

NewRoute prepares the route to be used in matching.

func (*Route) ActionPath added in v0.17.1

func (route *Route) ActionPath() string

type RouteMatch

type RouteMatch struct {
	Action           string // e.g. 404
	ControllerName   string // e.g. Application
	MethodName       string // e.g. ShowApp
	FixedParams      []string
	Params           map[string][]string // e.g. {id: 123}
	TypeOfController *ControllerType     // The controller type
	ModuleSource     *Module             // The module
}

type Router

type Router struct {
	Routes []*Route
	Tree   *pathtree.Node
	Module string // The module the route is associated with
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter(routesPath string) *Router

func (*Router) Refresh

func (router *Router) Refresh() (err *Error)

Refresh re-reads the routes file and re-calculates the routing table. Returns an error if a specified action could not be found.

func (*Router) Reverse

func (router *Router) Reverse(action string, argValues map[string]string) (ad *ActionDefinition)

func (*Router) ReverseError added in v1.0.0

func (router *Router) ReverseError(action string, argValues map[string]string, req *Request) (ad *ActionDefinition, err error)

func (*Router) Route

func (router *Router) Route(req *Request) (routeMatch *RouteMatch)

type ServerContext added in v0.18.0

type ServerContext interface {
	GetRequest() ServerRequest
	GetResponse() ServerResponse
}

type ServerCookie added in v0.18.0

type ServerCookie interface {
	GetValue() string
}

Expected response for FROM_HTTP_COOKIE type (if implemented)

type ServerEngine added in v0.18.0

type ServerEngine interface {
	// Initialize the server (non blocking)
	Init(init *EngineInit)
	// Starts the server. This will block until server is stopped
	Start()
	// Fires a new event to the server
	Event(event Event, args interface{}) EventResponse
	// Returns the engine instance for specific calls
	Engine() interface{}
	// Returns the engine Name
	Name() string
	// Returns any stats
	Stats() map[string]interface{}
}

type ServerEngineEmpty added in v0.18.0

type ServerEngineEmpty struct {
}

An empty server engine

func (*ServerEngineEmpty) Get added in v0.18.0

func (e *ServerEngineEmpty) Get(_ string) interface{}

func (*ServerEngineEmpty) Set added in v0.18.0

func (e *ServerEngineEmpty) Set(_ string, _ interface{}) bool

type ServerHeader added in v0.18.0

type ServerHeader interface {
	SetCookie(cookie string)                              // Sets the cookie
	GetCookie(key string) (value ServerCookie, err error) // Gets the cookie
	Set(key string, value string)
	Add(key string, value string)
	Del(key string)
	Get(key string) (value []string)
	GetKeys() (headerKeys []string)
	SetStatus(statusCode int)
}

Expected response for HTTP_SERVER_HEADER type (if implemented)

type ServerMultipartForm added in v0.18.0

type ServerMultipartForm interface {
	GetFiles() map[string][]*multipart.FileHeader
	GetValues() url.Values
	RemoveAll() error
}

Expected response for HTTP_MULTIPART_FORM

type ServerMux added in v0.21.0

type ServerMux struct {
	PathPrefix string      // The path prefix
	Callback   interface{} // The callback interface as appropriate to the server
}

The route handler structure

type ServerMuxList added in v0.21.0

type ServerMuxList []ServerMux

A list of handlers used for adding special route functions

func (ServerMuxList) Find added in v0.21.0

func (r ServerMuxList) Find(path string) (interface{}, bool)

Search function, returns the largest path matching this

func (ServerMuxList) Len added in v0.21.0

func (r ServerMuxList) Len() int

Sorting function

func (ServerMuxList) Less added in v0.21.0

func (r ServerMuxList) Less(i, j int) bool

Sorting function

func (ServerMuxList) Swap added in v0.21.0

func (r ServerMuxList) Swap(i, j int)

Sorting function

type ServerRequest added in v0.18.0

type ServerRequest interface {
	GetRaw() interface{}
	Get(theType int) (interface{}, error)
	Set(theType int, theValue interface{}) bool
}

Callback ServerRequest type

type ServerResponse added in v0.18.0

type ServerResponse interface {
	ServerRequest
}

Callback ServerResponse type

type ServerWebSocket added in v0.18.0

type ServerWebSocket interface {
	ServerResponse
	MessageSendJSON(v interface{}) error
	MessageReceiveJSON(v interface{}) error
	MessageSend(v interface{}) error
	MessageReceive(v interface{}) error
}

Callback WebSocket type

type SessionCookieEngine added in v0.21.0

type SessionCookieEngine struct {
	ExpireAfterDuration time.Duration
}

The session cookie engine

func NewSessionCookieEngine added in v0.21.0

func NewSessionCookieEngine() *SessionCookieEngine

For testing purposes this engine is used

func (*SessionCookieEngine) Decode added in v0.21.0

func (cse *SessionCookieEngine) Decode(c *Controller)

Decode the session information from the cookie retrieved from the controller request

func (*SessionCookieEngine) DecodeCookie added in v0.21.0

func (cse *SessionCookieEngine) DecodeCookie(cookie ServerCookie, s session.Session)

Exposed only for testing purposes

func (*SessionCookieEngine) Encode added in v0.21.0

func (cse *SessionCookieEngine) Encode(c *Controller)

Encode the session information to the cookie, set the cookie on the controller

func (*SessionCookieEngine) GetCookie added in v0.21.0

func (cse *SessionCookieEngine) GetCookie(s session.Session) *http.Cookie

Convert session to cookie

type SessionEngine added in v0.21.0

type SessionEngine interface {
	Decode(c *Controller) // Called to decode the session information on the controller
	Encode(c *Controller) // Called to encode the session information on the controller
}

The session engine provides an interface to allow for storage of session data

var (
	CurrentSessionEngine SessionEngine
)

type SourceLine added in v0.14.0

type SourceLine struct {
	Source  string
	Line    int
	IsError bool
}

SourceLine structure to hold the per-source-line details.

type StreamWriter added in v0.18.0

type StreamWriter interface {
	WriteStream(name string, contentlen int64, modtime time.Time, reader io.Reader) error
}

type Template

type Template interface {
	// The name of the template.
	Name() string // Name of template
	// The content of the template as a string (Used in error handling).
	Content() []string // Content
	// Called by the server to render the template out the io.Writer, context contains the view args to be passed to the template.
	Render(wr io.Writer, context interface{}) error
	// The full path to the file on the disk.
	Location() string // Disk location
}

type TemplateEngine added in v0.16.0

type TemplateEngine interface {
	// prase template string and add template to the set.
	ParseAndAdd(basePath *TemplateView) error

	// returns Template corresponding to the given templateName, or nil
	Lookup(templateName string) Template

	// Fired by the template loader when events occur
	Event(event Event, arg interface{})

	// returns true if this engine should be used to parse the file specified in baseTemplate
	Handles(templateView *TemplateView) bool

	// returns the name of the engine
	Name() string
}

type TemplateLoader

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

TemplateLoader object handles loading and parsing of templates. Everything below the application's views directory is treated as a template.

func NewTemplateLoader

func NewTemplateLoader(paths []string) *TemplateLoader

func (*TemplateLoader) CreateTemplateEngine added in v0.16.0

func (loader *TemplateLoader) CreateTemplateEngine(templateEngineName string) (TemplateEngine, error)

Sets the template name from Config Sets the template API methods for parsing and storing templates before rendering

func (*TemplateLoader) Refresh

func (loader *TemplateLoader) Refresh() (err *Error)

Refresh method scans the views directory and parses all templates as Go Templates. If a template fails to parse, the error is set on the loader. (It's awkward to refresh a single Go Template)

func (*TemplateLoader) Template

func (loader *TemplateLoader) Template(name string) (tmpl Template, err error)

DEPRECATED Use TemplateLang, will be removed in future release

func (*TemplateLoader) TemplateLang added in v0.16.0

func (loader *TemplateLoader) TemplateLang(name, lang string) (tmpl Template, err error)

func (*TemplateLoader) WatchDir

func (loader *TemplateLoader) WatchDir(info os.FileInfo) bool

WatchDir returns true of directory doesn't start with . (dot) otherwise false

func (*TemplateLoader) WatchFile

func (loader *TemplateLoader) WatchFile(basename string) bool

WatchFile returns true of file doesn't start with . (dot) otherwise false

type TemplateView added in v0.16.0

type TemplateView struct {
	TemplateName string // The name of the view
	FilePath     string // The file path (view relative)
	BasePath     string // The file system base path
	FileBytes    []byte // The file loaded
	EngineType   string // The name of the engine used to render the view
}

The template view information

func NewBaseTemplate added in v0.16.0

func NewBaseTemplate(templateName, filePath, basePath string, fileBytes []byte) *TemplateView

func (*TemplateView) Content added in v0.16.0

func (i *TemplateView) Content() (content []string)

func (*TemplateView) Location added in v0.16.0

func (i *TemplateView) Location() string

type URL added in v0.17.1

type URL struct {
	Domain
}

func ValidURL added in v0.17.1

func ValidURL() URL

func (URL) DefaultMessage added in v0.17.1

func (u URL) DefaultMessage() string

func (URL) IsSatisfied added in v0.17.1

func (u URL) IsSatisfied(obj interface{}) bool

type Validation

type Validation struct {
	Errors     []*ValidationError
	Request    *Request
	Translator func(locale, message string, args ...interface{}) string
	// contains filtered or unexported fields
}

Validation context manages data validation and error messages.

func (*Validation) Check

func (v *Validation) Check(obj interface{}, checks ...Validator) *ValidationResult

Check applies a group of validators to a field, in order, and return the ValidationResult from the first one that fails, or the last one that succeeds.

func (*Validation) Clear

func (v *Validation) Clear()

Clear *all* ValidationErrors

func (*Validation) Domain added in v0.17.1

func (v *Validation) Domain(str string) *ValidationResult

func (*Validation) Email

func (v *Validation) Email(str string) *ValidationResult

func (*Validation) Error

func (v *Validation) Error(message string, args ...interface{}) *ValidationResult

Error adds an error to the validation context.

func (*Validation) ErrorKey added in v0.18.0

func (v *Validation) ErrorKey(message string, args ...interface{}) *ValidationResult

Error adds an error to the validation context.

func (*Validation) ErrorMap

func (v *Validation) ErrorMap() map[string]*ValidationError

ErrorMap returns the errors mapped by key. If there are multiple validation errors associated with a single key, the first one "wins". (Typically the first validation will be the more basic).

func (*Validation) FilePath added in v0.17.1

func (v *Validation) FilePath(str string, m int) *ValidationResult

func (*Validation) HasErrors

func (v *Validation) HasErrors() bool

HasErrors returns true if there are any (ie > 0) errors. False otherwise.

func (*Validation) IPAddr added in v0.17.1

func (v *Validation) IPAddr(str string, cktype ...int) *ValidationResult

func (*Validation) Keep

func (v *Validation) Keep()

Keep tells revel to set a flash cookie on the client to make the validation errors available for the next request. This is helpful when redirecting the client after the validation failed. It is good practice to always redirect upon a HTTP POST request. Thus one should use this method when HTTP POST validation failed and redirect the user back to the form.

func (*Validation) Length

func (v *Validation) Length(obj interface{}, n int) *ValidationResult

func (*Validation) MacAddr added in v0.17.1

func (v *Validation) MacAddr(str string) *ValidationResult

func (*Validation) Match

func (v *Validation) Match(str string, regex *regexp.Regexp) *ValidationResult

func (*Validation) Max

func (v *Validation) Max(n int, max int) *ValidationResult

func (*Validation) MaxFloat added in v0.18.0

func (v *Validation) MaxFloat(n float64, max float64) *ValidationResult

func (*Validation) MaxSize

func (v *Validation) MaxSize(obj interface{}, max int) *ValidationResult

func (*Validation) Min

func (v *Validation) Min(n int, min int) *ValidationResult

func (*Validation) MinFloat added in v0.18.0

func (v *Validation) MinFloat(n float64, min float64) *ValidationResult

func (*Validation) MinSize

func (v *Validation) MinSize(obj interface{}, min int) *ValidationResult

func (*Validation) PureText added in v0.17.1

func (v *Validation) PureText(str string, m int) *ValidationResult

func (*Validation) Range

func (v *Validation) Range(n, min, max int) *ValidationResult

func (*Validation) RangeFloat added in v0.18.0

func (v *Validation) RangeFloat(n, min, max float64) *ValidationResult

func (*Validation) Required

func (v *Validation) Required(obj interface{}) *ValidationResult

Required tests that the argument is non-nil and non-empty (if string or list)

func (*Validation) URL added in v0.17.1

func (v *Validation) URL(str string) *ValidationResult

func (*Validation) ValidationResult added in v0.18.0

func (v *Validation) ValidationResult(ok bool) *ValidationResult

Error adds an error to the validation context.

type ValidationError

type ValidationError struct {
	Message, Key string
}

ValidationError simple struct to store the Message & Key of a validation error

func (*ValidationError) String

func (e *ValidationError) String() string

String returns the Message field of the ValidationError struct.

type ValidationResult

type ValidationResult struct {
	Error      *ValidationError
	Ok         bool
	Locale     string
	Translator func(locale, message string, args ...interface{}) string
}

ValidationResult is returned from every validation method. It provides an indication of success, and a pointer to the Error (if any).

func (*ValidationResult) Key

Key sets the ValidationResult's Error "key" and returns itself for chaining

func (*ValidationResult) Message

func (r *ValidationResult) Message(message string, args ...interface{}) *ValidationResult

Message sets the error message for a ValidationResult. Returns itself to allow chaining. Allows Sprintf() type calling with multiple parameters

func (*ValidationResult) MessageKey added in v0.18.0

func (r *ValidationResult) MessageKey(message string, args ...interface{}) *ValidationResult

Allow a message key to be passed into the validation result. The Validation has already setup the translator to translate the message key

type Validator

type Validator interface {
	IsSatisfied(interface{}) bool
	DefaultMessage() string
}

type Watcher

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

Watcher allows listeners to register to be notified of changes under a given directory.

func NewWatcher

func NewWatcher() *Watcher

func (*Watcher) Listen

func (w *Watcher) Listen(listener Listener, roots ...string)

Listen registers for events within the given root directories (recursively).

func (*Watcher) Notify

func (w *Watcher) Notify() *Error

Notify causes the watcher to forward any change events to listeners. It returns the first (if any) error returned.

func (*Watcher) NotifyWhenUpdated added in v0.11.0

func (w *Watcher) NotifyWhenUpdated(listener Listener, watcher *fsnotify.Watcher)

NotifyWhenUpdated notifies the watcher when a file event is received.

type When

type When int
const (
	BEFORE When = iota
	AFTER
	PANIC
	FINALLY
)

type WriteFlusher

type WriteFlusher interface {
	io.Writer     // An IO Writer
	io.Closer     // A closure
	Flush() error /// A flush function
}

WriteFlusher interface for compress writer

Directories

Path Synopsis
Package logger contains filters and handles for the logging utilities in Revel.
Package logger contains filters and handles for the logging utilities in Revel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL