Documentation ¶
Overview ¶
Package MVC provides a lightweight, testable and efficient Model-View-Controller framework. The main features are testable controllers, session support, parameterised routes and support for a Haml-like template language.
The main component is the mvc handler, instantiated like this:
handler := mvc.NewMvcHandler()
Once you have have an MVC handler, you can begin adding routes, which can contained named parameters. Parameters can be specified by surrounding the parameter name with curly brackets, like this:
handler.AddRoute("Hello route", "/Hello/{name}", mvc.GET, GreetingController)
The code above creates a route named 'Hello route'. The route will match requests to '/Hello/...', and will associate the value passed in the URL with a parameter called 'name'. Finally, this route will be handled by a function named GreetingController, which might look like this:
func GreetingController(ctx *mvc.WebContext, params url.Values) mvc.ControllerResult { name := params.Get("name") if name == "" { name = "there" } wr := NewHelloWorldWriter(name) return mvc.Haml(wr, name, ctx) }
The Greeting Controller retrieves the parameter called 'name' and passes it to a Haml template to render to the user. Note that the function returns a mvc.ControllerResult object, which allows us to call this controller method in a test scenario and test the resulting ControllerResult.
Index ¶
- Variables
- func NotFoundFunc(w http.ResponseWriter, r *http.Request)
- func StrongRandomString() string
- type Authentication
- type AuthenticationDatabase
- func (auth *AuthenticationDatabase) CreateUser(sessionId, ipAddress, username, emailAddress, encryptedPassword string) (userId int64, err error)
- func (auth *AuthenticationDatabase) DeleteAuth(sessionId string)
- func (auth *AuthenticationDatabase) GetAuth(sessionId string) (authentication *Authentication, user *User, err error)
- func (auth *AuthenticationDatabase) GetUserById(id int64) (u *User, err error)
- func (auth *AuthenticationDatabase) GetUserByUsername(username string) (user *User, err error)
- func (auth *AuthenticationDatabase) GetUserByUsernameAndPassword(username, password string) (user *User, err error)
- func (auth *AuthenticationDatabase) InsertAuthentication(sessionId string, userId int64, ipAddress string) error
- type Authenticator
- func (auth *Authenticator) CreateUser(sessionId, ipAddress, username, emailAddress, password string) (user *User, err error)
- func (auth *Authenticator) GetAuthentication(sessionId, ipAddress string) (authentication *Authentication, user *User, err error)
- func (auth *Authenticator) InsertAuthentication(sessionId string, userId int64, ipAddress string) error
- func (auth *Authenticator) Login(username, password, ipAddress, sessionId string) (*User, error)
- func (auth *Authenticator) Logout(sessionId string)
- type ControllerFunc
- type ControllerResult
- func Error(errorMessage string, ctx *WebContext) ControllerResult
- func Haml(templ HamlTemplate, data interface{}, ctx *WebContext) ControllerResult
- func Json(data interface{}, ctx *WebContext) ControllerResult
- func Redirect(url string, ctx *WebContext) ControllerResult
- func Template(templateName string, data interface{}, ctx *WebContext) ControllerResult
- type ErrorResult
- type HamlResult
- type HamlTemplate
- type HttpMethod
- type JsonResult
- type MismatchedParameterCountError
- type MvcHandler
- type RedirectResult
- type Route
- type RouteHandler
- func (rh *RouteHandler) AddNewRoute(name string, path string, method HttpMethod, controllerFunc ControllerFunc)
- func (rh *RouteHandler) AddRoute(route *Route)
- func (rh *RouteHandler) GetRoute(path string, method string) (*Route, bool)
- func (rh *RouteHandler) GetRouteFromRequest(r *http.Request) (*Route, bool)
- type Session
- type SessionManager
- type TemplateResult
- type User
- type WebContext
Constants ¶
This section is empty.
Variables ¶
var DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var ErrInvalidUsernamePassword error = errors.New("Invalid username and password combination")
var SESSION_IDENT = "gomvc_sessionid"
var UnrecognisedIP error = errors.New("Unrecognised IP Address")
var UnrecognisedSessionId = errors.New("Unrecognised Session Id")
Functions ¶
func NotFoundFunc ¶
func NotFoundFunc(w http.ResponseWriter, r *http.Request)
TODO: Fill out this method
Types ¶
type Authentication ¶
type AuthenticationDatabase ¶
type AuthenticationDatabase struct {
// contains filtered or unexported fields
}
func NewAuthenticationDatabase ¶
func NewAuthenticationDatabase() *AuthenticationDatabase
func (*AuthenticationDatabase) CreateUser ¶
func (auth *AuthenticationDatabase) CreateUser(sessionId, ipAddress, username, emailAddress, encryptedPassword string) (userId int64, err error)
func (*AuthenticationDatabase) DeleteAuth ¶
func (auth *AuthenticationDatabase) DeleteAuth(sessionId string)
func (*AuthenticationDatabase) GetAuth ¶
func (auth *AuthenticationDatabase) GetAuth(sessionId string) (authentication *Authentication, user *User, err error)
func (*AuthenticationDatabase) GetUserById ¶
func (auth *AuthenticationDatabase) GetUserById(id int64) (u *User, err error)
func (*AuthenticationDatabase) GetUserByUsername ¶
func (auth *AuthenticationDatabase) GetUserByUsername(username string) (user *User, err error)
func (*AuthenticationDatabase) GetUserByUsernameAndPassword ¶
func (auth *AuthenticationDatabase) GetUserByUsernameAndPassword(username, password string) (user *User, err error)
func (*AuthenticationDatabase) InsertAuthentication ¶
func (auth *AuthenticationDatabase) InsertAuthentication(sessionId string, userId int64, ipAddress string) error
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
func NewAuthenticator ¶
func NewAuthenticator() *Authenticator
func (*Authenticator) CreateUser ¶
func (auth *Authenticator) CreateUser(sessionId, ipAddress, username, emailAddress, password string) (user *User, err error)
func (*Authenticator) GetAuthentication ¶
func (auth *Authenticator) GetAuthentication(sessionId, ipAddress string) (authentication *Authentication, user *User, err error)
func (*Authenticator) InsertAuthentication ¶
func (auth *Authenticator) InsertAuthentication(sessionId string, userId int64, ipAddress string) error
func (*Authenticator) Login ¶
func (auth *Authenticator) Login(username, password, ipAddress, sessionId string) (*User, error)
func (*Authenticator) Logout ¶
func (auth *Authenticator) Logout(sessionId string)
type ControllerFunc ¶
type ControllerFunc func(ctx *WebContext, params url.Values) ControllerResult
ControllerFunc is the signature expected for a controller function
type ControllerResult ¶
type ControllerResult interface {
Execute()
}
ControllerResult is the return interface value from a controller.
func Error ¶
func Error(errorMessage string, ctx *WebContext) ControllerResult
func Haml ¶
func Haml(templ HamlTemplate, data interface{}, ctx *WebContext) ControllerResult
Haml is a utility method to create a controller result for executing Haml templates
func Json ¶
func Json(data interface{}, ctx *WebContext) ControllerResult
Json is a utility function for creating ControllerResults to return Json to the client
func Redirect ¶
func Redirect(url string, ctx *WebContext) ControllerResult
func Template ¶
func Template(templateName string, data interface{}, ctx *WebContext) ControllerResult
Template is a utility method to create a controller result for executing go templates
type ErrorResult ¶
type ErrorResult struct { Context *WebContext Message string }
Errors
func (*ErrorResult) Execute ¶
func (e *ErrorResult) Execute()
type HamlResult ¶
type HamlResult struct { Template HamlTemplate Data interface{} Context *WebContext }
HamlResult contains the template, data to display and the web context within which we are working
func (*HamlResult) Execute ¶
func (h *HamlResult) Execute()
Execute() executes the Haml template and writes the response to the ResponseWriter
type HamlTemplate ¶
type HamlTemplate interface { SetData(data interface{}) Execute(http.ResponseWriter, *http.Request) }
HamlTemplate is the interface definition for executing a generated Haml template
type HttpMethod ¶
type HttpMethod int
const ( GET HttpMethod = iota HEAD // do we care about this? POST PUT // and this? DELETE )
HttpMethods that we will handle
type JsonResult ¶
type JsonResult struct { Data interface{} Context *WebContext }
JsonResult is a ControllerResult for returning Json to the client
func (*JsonResult) Execute ¶
func (j *JsonResult) Execute()
Execute marshalls the Json object and returns the result to the client
type MismatchedParameterCountError ¶
type MismatchedParameterCountError int
func (MismatchedParameterCountError) Error ¶
func (e MismatchedParameterCountError) Error() string
type MvcHandler ¶
type MvcHandler struct { Routes *RouteHandler Sessions *SessionManager SessionsEnabled bool Templates *template.Template // Go Html Templates NotFoundHandler func(http.ResponseWriter, *http.Request) Authenticator *Authenticator // contains filtered or unexported fields }
MvcHandler provides routing, sessions and an mvc patter for the http.Handle() function
func NewMvcHandler ¶
func NewMvcHandler() *MvcHandler
NewMvcHandler creates an http handler for the MVC package. You can use this handler to route requests from Go's http server like this: http.Handle("/", handler)
func (*MvcHandler) AddRoute ¶
func (mvc *MvcHandler) AddRoute(name string, path string, method HttpMethod, controllerFunc ControllerFunc)
Adds a new route to the MVC handler
func (*MvcHandler) ServeHTTP ¶
func (mvc *MvcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
Main handler function, responsible for multiplexing routes and adding session data
func (*MvcHandler) SetTemplates ¶
func (mvc *MvcHandler) SetTemplates(template *template.Template)
Adds all (parsed) go Templates to the MVC Hanlder. Template value should be the result of calling 'template.ParseFiles(...)'
type RedirectResult ¶
type RedirectResult struct { Context *WebContext // contains filtered or unexported fields }
Redirects
func (*RedirectResult) Execute ¶
func (r *RedirectResult) Execute()
type Route ¶
type Route struct { Name string Spec string Regexp *regexp.Regexp Params []string Method HttpMethod Controller ControllerFunc }
Route encapsulates infomration needed to route http requests, including the regex it uses to match requests, the parameter names to use in value mapping and the controller to which the route should be mapped
func NewRoute ¶
func NewRoute(name string, spec string, method HttpMethod, controllerFunc ControllerFunc) *Route
NewRoute creates a Route from a spec (formatted query string, e.g. /Products/{Id})
type RouteHandler ¶
type RouteHandler struct {
// contains filtered or unexported fields
}
Route Handler multiplexes URL requests to controller functions.
func NewRouteHandler ¶
func NewRouteHandler() *RouteHandler
NewRouteHandler initialises and returns a new route handler.
func (*RouteHandler) AddNewRoute ¶
func (rh *RouteHandler) AddNewRoute(name string, path string, method HttpMethod, controllerFunc ControllerFunc)
AddNewRoute associates a route to a controller and adds it to the RouteHandler
func (*RouteHandler) AddRoute ¶
func (rh *RouteHandler) AddRoute(route *Route)
AddRoute adds an existing route to the RouteHandler
func (*RouteHandler) GetRoute ¶
func (rh *RouteHandler) GetRoute(path string, method string) (*Route, bool)
GetRoute retrieves a route given a URL and request method
func (*RouteHandler) GetRouteFromRequest ¶
func (rh *RouteHandler) GetRouteFromRequest(r *http.Request) (*Route, bool)
GetRouteFromRequests returns a route from an http.Request instance.
type Session ¶
type Session struct { Id string // contains filtered or unexported fields }
Stores session information for an individual user
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
func GetSessionManager ¶
func GetSessionManager() *SessionManager
Only to be used as a stand-alone session manager Stores and returns a singleton instance
func (*SessionManager) GetSession ¶
func (sm *SessionManager) GetSession(w http.ResponseWriter, r *http.Request) *Session
Gets the session associated with a particular request and handles maintaining the session in the response
type TemplateResult ¶
type TemplateResult struct { TemplateName string Data interface{} Context *WebContext }
TemplateResult combines a Go Template and the data for its execution context
func (*TemplateResult) Execute ¶
func (t *TemplateResult) Execute()
Execute executes the template and writes the result to the Http response
type WebContext ¶
type WebContext struct { ResponseWriter http.ResponseWriter Request *http.Request Session *Session User *User // contains filtered or unexported fields }
WebContext provides access to request and session information
func GetTestControllerParameters ¶
func GetTestControllerParameters() (ctx *WebContext, params url.Values)
GetTestControllerParameters returns empty WebContext and Values objects for testing
func NewWebContext ¶
func NewWebContext(m *MvcHandler, w http.ResponseWriter, r *http.Request, s *Session) *WebContext
NewWebContext creates a new Web Context
func (*WebContext) CreateUser ¶
func (ctx *WebContext) CreateUser(username, password, emailAddress string) (user *User, err error)
func (*WebContext) IsUserLoggedIn ¶
func (ctx *WebContext) IsUserLoggedIn() bool
func (*WebContext) Logout ¶
func (ctx *WebContext) Logout()