mvc

package module
v0.0.0-...-97077ef Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2013 License: GPL-2.0 Imports: 20 Imported by: 3

README

Go-MVC - Testable MVC Framework for Go

Go-MVC is a lightweight MVC framework for the Go language. Its goals are to provide an efficient, testable framework for creating web applications.

Build Status

Go-MVC's main features are:

  • Routing with Named Parameters
  • Testable controllers
  • Session support
  • Support for different templating engines and Json requests

Development is still underway, so contributions are encouraged.

Routing with Named Parameters

Go-MVC lets you create routes with named parameters. For example, you can create a route as follows:

mvcHandle := mvc.NewMvcHandler()
mvcHandle.AddRoute("Hello", "/Hello/{name}", mvc.GET, GreetingController)
http.Handle("/", mvcHandle)
http.ListenAndServe("localhost:8080", nil)

The code above creates a route named 'Hello' that intercepts GET requests for routes that match 'localhost:8080/Hello/*' and directs them to a controller named 'GreetingController'.

Controller methods accept a parameter called 'params' which contains query string parameters, form post parameters and values from named routes. You can then access the values inside of your controller. For example, if a request is made to 'http://localhost:8080/Hello/World', you could access the value of 'name' as follows:

name := params.Get("name")

Testable Controllers

Go-MVC provides a clean separation between controller logic and view presentation, allowing for easy testing. For example, the following controller converts a URL part (specified in a route: see below) to uppercase:

func ToUpperController(ctx *mvc.WebContext, params url.Values) mvc.ControllerResults {
    in := params.Get("input")
	upper := strings.ToUpper(in)
	hamlWriter := NewViewWriter(upper)
	return mvc.Haml(hamlWriter, upper, ctx)
}

The code above could be tested like this:

func ToUpperController_Test(t *testing.T) {
    ctx, params = GetTestControllerParameters()
	params.Add("input", "tesTIng")

	result := ToUpperController(ctx, params)
	hamlRes := res.(*HamlResult)
	if hamlRes.Data != "TESTING" {
	    t.Error("Data not as expected: " + hamlRes.Data)
	}
}

Sessions

Go-MVC provides server-side sessions transparently. As a developer you just add and remove items from the session:

var val interface{}
if val, exists = ctx.Session.Get("count"); !exists {
	val = -1
}

count := val.(int)
count++
ctx.Session.Put("count", count)

Copyright 2013 Travis Simon

Licensed under the GNU General Public License Version 2.0 (or later); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:

http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

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

Constants

This section is empty.

Variables

View Source
var DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
View Source
var ErrInvalidUsernamePassword error = errors.New("Invalid username and password combination")
View Source
var SESSION_IDENT = "gomvc_sessionid"
View Source
var UnrecognisedIP error = errors.New("Unrecognised IP Address")
View Source
var UnrecognisedSessionId = errors.New("Unrecognised Session Id")

Functions

func NotFoundFunc

func NotFoundFunc(w http.ResponseWriter, r *http.Request)

TODO: Fill out this method

func StrongRandomString

func StrongRandomString() string

Creates a random string

Types

type Authentication

type Authentication struct {
	SessionId string
	UserId    int64
	IpAddress string
}

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

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

func (*Route) GetParameterValues

func (r *Route) GetParameterValues(path string) (url.Values, error)

GetParameterValues extracts the values implicitly passed in a URL. E.g., for a route of /p/{Id}, the path: /p/23 would return {Id:23}

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

func NewSession

func NewSession(sessionId string) *Session

Creates a new session for the given id

func (*Session) Get

func (s *Session) Get(key string) (interface{}, bool)

returns the item if found, nil if not Also returns a boolean indicated whether the item was found

func (*Session) Put

func (s *Session) Put(key string, value interface{})

stores a value in the session

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 NewSessionManager

func NewSessionManager() *SessionManager

Returns a new session manager

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 User

type User struct {
	Id                   int64
	Username             string
	Password             string
	RecoveryEmailAddress string
}

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

func (ctx *WebContext) Login(username, password string) (*User, error)

func (*WebContext) Logout

func (ctx *WebContext) Logout()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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