mvc

package
v8.5.7+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2017 License: BSD-3-Clause Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultViewExt = ".html"

DefaultViewExt is the default extension if `view.Name `is missing, but note that it doesn't care about the app.RegisterView(iris.$VIEW_ENGINE("./$dir", "$ext"))'s $ext. so if you don't use the ".html" as extension for your files you have to append the extension manually into the `view.Name` or change this global variable.

Functions

This section is empty.

Types

type ActivatePayload

type ActivatePayload = activator.ActivatePayload

ActivatePayload contains the necessary information and the ability to alt a controller's registration options, i.e the binder.

With `ActivatePayload` the `Controller` can register custom routes or modify the provided values that will be binded to the controller later on.

Look the `mvc/activator#ActivatePayload` for its implementation.

A shortcut for the `mvc/activator#ActivatePayload`, useful when `OnActivate` is being used.

type C

type C struct {
	// The Name of the `C` controller.
	Name string
	// The current context.Context.
	//
	// we have to name it for two reasons:
	// 1: can't ignore these via reflection, it doesn't give an option to
	// see if the functions is derived from another type.
	// 2: end-developer may want to use some method functions
	// or any fields that could be conflict with the context's.
	Ctx context.Context
}

C is the lightweight BaseController type as an alternative of the `Controller` struct type. It contains only the Name of the controller and the Context, it's the best option to balance the performance cost reflection uses if your controller uses the new func output values dispatcher feature; func(c *ExampleController) Get() string | (string, string) | (string, int) | int | (int, string | (string, error) | bool | (any, bool) | error | (int, error) | (customStruct, error) | customStruct | (customStruct, int) | (customStruct, string) | Result or (Result, error) where Get is an HTTP Method func.

Look `core/router#APIBuilder#Controller` method too.

It completes the `activator.BaseController` interface.

Example at: https://github.com/kataras/iris/tree/master/_examples/mvc/overview/web/controllers. Example usage at: https://github.com/kataras/iris/blob/master/mvc/method_result_test.go#L17.

func (*C) BeginRequest

func (c *C) BeginRequest(ctx context.Context)

BeginRequest starts the request by initializing the `Context` field.

func (*C) EndRequest

func (c *C) EndRequest(ctx context.Context)

EndRequest does nothing, is here to complete the `BaseController` interface.

func (*C) SetName

func (c *C) SetName(name string)

SetName sets the controller's full name. It's called internally.

type Controller

type Controller struct {
	// Name contains the current controller's full name.
	//
	// doesn't change on different paths.
	Name string

	// request path and its parameters, read-write.
	// Path is the current request path, if changed then it redirects.
	Path string
	// Params are the request path's parameters, i.e
	// for route like "/user/{id}" and request to "/user/42"
	// it contains the "id" = 42.
	Params *context.RequestParams

	// some info read and write,
	// can be already set-ed by previous handlers as well.
	Status int
	Values *memstore.Store

	// view read and write,
	// can be already set-ed by previous handlers as well.
	Layout string
	Tmpl   string
	Data   map[string]interface{}

	ContentType string
	Text        string // response as string

	// give access to the request context itself.
	Ctx context.Context
	// contains filtered or unexported fields
}

Controller is the base controller for the high level controllers instances.

This base controller is used as an alternative way of building APIs, the controller can register all type of http methods.

Keep note that controllers are bit slow because of the reflection use however it's as fast as possible because it does preparation before the serve-time handler but still remains slower than the low-level handlers such as `Handle, Get, Post, Put, Delete, Connect, Head, Trace, Patch`.

All fields that are tagged with iris:"persistence"` or binded are being persistence and kept the same between the different requests.

An Example Controller can be:

type IndexController struct {
	Controller
}
func (c *IndexController) Get() {
	c.Tmpl = "index.html"
	c.Data["title"] = "Index page"
	c.Data["message"] = "Hello world!"
}

Usage: app.Controller("/", new(IndexController))

Another example with bind:

type UserController struct {
	mvc.Controller

	DB        *DB
	CreatedAt time.Time
}

// Get serves using the User controller when HTTP Method is "GET".

func (c *UserController) Get() {
	c.Tmpl = "user/index.html"
	c.Data["title"] = "User Page"
	c.Data["username"] = "kataras " + c.Params.Get("userid")
	c.Data["connstring"] = c.DB.Connstring
	c.Data["uptime"] = time.Now().Sub(c.CreatedAt).Seconds()
}

Usage: app.Controller("/user/{id:int}", new(UserController), db, time.Now()) Note: Binded values of context.Handler type are being recognised as middlewares by the router.

Look `core/router/APIBuilder#Controller` method too.

It completes the `activator.BaseController` interface.

func (*Controller) BeginRequest

func (c *Controller) BeginRequest(ctx context.Context)

BeginRequest starts the main controller it initialize the Ctx and other fields.

It's called internally. End-Developer can ovverride it but it still MUST be called.

func (*Controller) EndRequest

func (c *Controller) EndRequest(ctx context.Context)

EndRequest is the final method which will be executed before response sent.

It checks for the fields and calls the necessary context's methods to modify the response to the client.

It's called internally. End-Developer can ovveride it but still should be called at the end.

func (*Controller) RelPath

func (c *Controller) RelPath() string

RelPath tries to return the controller's name without the "Controller" prefix, all lowercase prefixed with slash and splited by slash appended with the rest of the request path. For example: If UserController and request path is "/user/messages" then it's "/messages" if UserPostController and request path is "/user/post" then it's "/" if UserProfile and request path is "/user/profile/likes" then it's "/likes"

It's useful for things like path checking and redirect.

func (*Controller) RelTmpl

func (c *Controller) RelTmpl() string

RelTmpl tries to return the controller's name without the "Controller" prefix, all lowercase splited by slash and suffixed by slash. For example: If UserController then it's "user/" if UserPostController then it's "user/post/" if UserProfile then it's "user/profile/".

It's useful to locate templates if the controller and views path have aligned names.

func (*Controller) Route

func (c *Controller) Route() context.RouteReadOnly

Route returns the current request controller's context read-only access route.

func (*Controller) SetName

func (c *Controller) SetName(name string)

SetName sets the controller's full name. It's called internally.

func (*Controller) Write

func (c *Controller) Write(contents []byte) (int, error)

Write writes to the client via the context's ResponseWriter. Controller completes the `io.Writer` interface for the shake of ease.

func (*Controller) Writef

func (c *Controller) Writef(format string, a ...interface{}) (int, error)

Writef formats according to a format specifier and writes to the response.

type HTML

type HTML = template.HTML

HTML wraps the "s" with the template.HTML in order to be marked as safe content, to be rendered as html and not escaped.

type Response

type Response struct {
	Code        int
	ContentType string
	Content     []byte

	// if not empty then content type is the text/plain
	// and content is the text as []byte.
	Text string
	// If not nil then it will fire that as "application/json" or the
	// "ContentType" if not empty.
	Object interface{}

	// If Path is not empty then it will redirect
	// the client to this Path, if Code is >= 300 and < 400
	// then it will use that Code to do the redirection, otherwise
	// StatusFound(302) or StatusSeeOther(303) for post methods will be used.
	// Except when err != nil.
	Path string

	// if not empty then fire a 400 bad request error
	// unless the Status is > 200, then fire that error code
	// with the Err.Error() string as its content.
	//
	// if Err.Error() is empty then it fires the custom error handler
	// if any otherwise the framework sends the default http error text based on the status.
	Err error
	Try func() int
}

Response completes the `methodfunc.Result` interface. It's being used as an alternative return value which wraps the status code, the content type, a content as bytes or as string and an error, it's smart enough to complete the request and send the correct response to the client.

func (Response) Dispatch

func (r Response) Dispatch(ctx context.Context)

Dispatch writes the response result to the context's response writer.

type Result

type Result interface {
	// Dispatch should sends the response to the context's response writer.
	Dispatch(ctx context.Context)
}

Result is a response dispatcher. All types that complete this interface can be returned as values from the method functions.

Example at: https://github.com/kataras/iris/tree/master/_examples/mvc/overview.

func Try

func Try(fn func() Result, failure ...Result) Result

Try will check if "fn" ran without any panics, using recovery, and return its result as the final response otherwise it returns the "failure" response if any, if not then a 400 bad request is being sent.

Example usage at: https://github.com/kataras/iris/blob/master/mvc/method_result_test.go.

type SessionController

type SessionController struct {
	Controller

	Manager *sessions.Sessions
	Session *sessions.Session
}

SessionController is a simple `Controller` implementation which requires a binded session manager in order to give direct access to the current client's session via its `Session` field.

func (*SessionController) BeginRequest

func (s *SessionController) BeginRequest(ctx context.Context)

BeginRequest calls the Controller's BeginRequest and tries to initialize the current user's Session.

func (*SessionController) OnActivate

func (s *SessionController) OnActivate(p *activator.ActivatePayload)

OnActivate called, once per application lifecycle NOT request, every single time the dev registers a specific SessionController-based controller. It makes sure that its "Manager" field is filled even if the caller didn't provide any sessions manager via the `app.Controller` function.

type View

type View struct {
	Name   string
	Layout string
	Data   interface{} // map or a custom struct.
	Code   int
	Err    error
}

View completes the `methodfunc.Result` interface. It's being used as an alternative return value which wraps the template file name, layout, (any) view data, status code and error. It's smart enough to complete the request and send the correct response to the client.

Example at: https://github.com/kataras/iris/blob/master/_examples/mvc/overview/web/controllers/hello_controller.go.

func (View) Dispatch

func (r View) Dispatch(ctx context.Context)

Dispatch writes the template filename, template layout and (any) data to the client. Completes the `Result` interface.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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