goweb

package module
v0.0.0-...-9fc0375 Latest Latest
Warning

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

Go to latest
Published: May 13, 2014 License: MIT Imports: 21 Imported by: 0

README

goweb

A modified version of goweb

Documentation

Documentation

Index

Constants

View Source
const CREATE_REST_METHOD string = "create"
View Source
const DELETEMANY_REST_METHOD string = "deletemany"
View Source
const DELETE_HTTP_METHOD string = "DELETE"
View Source
const DELETE_REST_METHOD string = "delete"
View Source
const EDIT_REST_METHOD string = "edit"
View Source
const ERR_NO_CONTROLLER string = "Routes must have a valid Controller"
View Source
const ERR_NO_MATCHING_ROUTE string = "No route found for that path"
View Source
const ERR_STANDARD_PREFIX string = "Oops, something went wrong: "

Error messages

View Source
const GET_HTTP_METHOD string = "GET"

HTTP Methods

View Source
const HTML_FORMAT string = "html"

Constant string for HTML format

View Source
const JSONP_CONTENT_TYPE string = "text/javascript"

JSONP Content-Type header value

View Source
const JSON_FORMAT string = "json"

Constant string for JSON format

View Source
const MOBILE_FORMAT string = "mbl"

Constant string for HTML format

View Source
const NEW_REST_METHOD string = "new"
View Source
const OPTIONS_HTTP_METHOD string = "OPTIONS"
View Source
const OPTIONS_REST_METHOD string = "options"
View Source
const POST_HTTP_METHOD string = "POST"
View Source
const PUT_HTTP_METHOD string = "PUT"
View Source
const RAW_FORMAT string = "raw"

Constant string for JSON format

View Source
const READMANY_REST_METHOD string = "readmany"
View Source
const READ_REST_METHOD string = "read"

RESTFUL Methods

View Source
const REQUEST_ALWAYS200_PARAMETER string = "always200"

Parameter name for Always200

View Source
const REQUEST_CALLBACK_PARAMETER string = "callback"

Parameter name for callback

View Source
const REQUEST_CONTEXT_PARAMETER string = "context"

Parameter name for Request Context

View Source
const REQUEST_METHOD_OVERRIDE_PARAMETER string = "method"

Parameter name for method override

View Source
const UPDATEMANY_REST_METHOD string = "updatemany"
View Source
const UPDATE_REST_METHOD string = "update"
View Source
const XML_FORMAT string = "xml"

Constant string for XML format

Variables

View Source
var CookieIsMissing error = errors.New("Cookie is missing")

CookieIsMissing is returned when a cookie is missing.

View Source
var CookieNotValid error = errors.New("Cookie and signed cookie do not match")

CookieNotValid is returned when the cookie and its signed counterpart do not match.

I.e. the cookie value has been tampered with.

View Source
var DEFAULT_FORMAT string = HTML_FORMAT

The fallback format if one cannot be determined by the request

View Source
var HashSecret string = "cX8Os0wfB6uCGZZSZHIi6rKsy7b0scE9"

HashSecret represents a secret string that is used to hash cookies.

For true security, this should be changed for each application.

View Source
var ROUTE_REGEX_PLACEHOLDER string = "(.*)"

Regex placeholder pattern

View Source
var (
	// SignedCookieFormat is the format string used to decide the name of the
	// signed cookie.
	SignedCookieFormat string = "%s_signed"
)
View Source
var SignedCookieIsMissing error = errors.New("Signed cookie is missing")

SignedCookieIsMissing is returned when the signed cookie is missing.

View Source
var UseStandardResponse = true

Functions

func AddFormatter

func AddFormatter(fs ...Formatter)

Adds a formatter decider

func ClearFormatters

func ClearFormatters()

Clears all formatters (including default internal ones)

func ConfigureDefaultFormatters

func ConfigureDefaultFormatters()

Adds the default formatters to goweb so that

func DeleteFromSession

func DeleteFromSession(obj interface{}, r *http.Request, w http.ResponseWriter)

func DictArgument

func DictArgument(values ...interface{}) map[string]interface{}

func Divisible

func Divisible(n, b int) bool

func EnableSession

func EnableSession(secret string)

func Hash

func Hash(s string) string

Hash one-way hashes a string with the private HashSecret value.

func ListenAndServe

func ListenAndServe(pattern string) error

Listens for incomming requests and handles them using the DefaultHttpHandler

The same as:

http.ListenAndServe(pattern, DefaultHttpHandler)

for more information see http.ListenAndServe

A typical example:

  func main() {
    goweb.Map("/people", peopleController)
	   goweb.ListenAndServe(":8080")
  }

func ListenAndServeInServer

func ListenAndServeInServer(server *http.Server) error

func ListenAndServeRoutes

func ListenAndServeRoutes(pattern string, r *RouteManager) error

func ListenAndServeRoutesTLS

func ListenAndServeRoutesTLS(pattern string, certFile string, keyFile string, r *RouteManager) error

func ListenAndServeTLS

func ListenAndServeTLS(pattern string, certFile string, keyFile string) error

func MapFormattedStatic

func MapFormattedStatic(pathPrefix string, obj interface{})

func MapFormattedStaticWithFunc

func MapFormattedStaticWithFunc(pathPrefix string, f func(cx *Context))

func MapRest

func MapRest(pathPrefix string, controller RestController)

Maps an entire RESTful set of routes to the specified RestController You only have to specify the methods that you require see rest_controller.go for the list of interfaces that can be satisfied

func MapStatic

func MapStatic(pathPrefix string, rootDirectory string)

Maps a path to a static directory

func MarshallInCookieSession

func MarshallInCookieSession(obj interface{}, r *http.Request, w http.ResponseWriter)

func RawHtml

func RawHtml(text string) template.HTML

func SetDefaultFormat

func SetDefaultFormat(format string)

func SetDefaultIndex

func SetDefaultIndex(path string)

func SetDocumentRoot

func SetDocumentRoot(root string)

Set the root for the rest html formating, formating is based on the method name(lower case)

func UnmarshalForm

func UnmarshalForm(form *map[string][]string, v interface{}, autofill bool) error

Fill a struct `v` from the values in `form`

func UnmarshallInCookieSession

func UnmarshallInCookieSession(obj interface{}, r *http.Request) error

Types

type Context

type Context struct {

	// The underlying http.Request for this context
	Request *http.Request

	// The underlying http.ResponseWriter for this context
	ResponseWriter http.ResponseWriter

	// A ParameterValueMap containing path parameters
	PathParams ParameterValueMap

	// The format that the response should be
	Format string

	// Mark the rest mothod for this context
	Rest RestContext

	// Stard Path
	PathWithOutSuffix string
	//parsed request bytes
	RequestData []byte
}

Object holding details about the request and responses

func (*Context) AddSignedCookie

func (c *Context) AddSignedCookie(cookie *http.Cookie) (*http.Cookie, error)

AddSignedCookie adds the specified cookie to the response and also adds an additional 'signed' cookie that is used to validate the cookies value when SignedCookie is called.

func (*Context) Fill

func (cx *Context) Fill(v interface{}, autofill bool) error

goweb.Context Helper function to fill a variable with the contents of the request body. The body will be decoded based on the content-type and an apropriate RequestDecoder automatically selected

func (*Context) FillAs

func (cx *Context) FillAs(v interface{}, autofill bool, ct string) error

func (*Context) GetCallback

func (c *Context) GetCallback() string

Gets the callback value from the request

func (*Context) GetRequestContext

func (c *Context) GetRequestContext() string

Gets the context value from the request

func (*Context) IsDelete

func (c *Context) IsDelete() bool

Checks whether the HTTP method is DELETE or not

func (*Context) IsGet

func (c *Context) IsGet() bool

Checks whether the HTTP method is GET or not

func (*Context) IsMobile

func (c *Context) IsMobile() bool

detect whether the client is from mobile device

func (*Context) IsOptions

func (c *Context) IsOptions() bool

Checks whether the HTTP method is OPTION or not

func (*Context) IsPost

func (c *Context) IsPost() bool

Checks whether the HTTP method is POST or not

func (*Context) IsPut

func (c *Context) IsPut() bool

Checks whether the HTTP method is PUT or not

func (*Context) Respond

func (c *Context) Respond(data interface{}, statusCode int, errors []string, context *Context, standard bool) error

RespondWith* methods

func (*Context) RespondWithData

func (c *Context) RespondWithData(data interface{}) error

Responds with the specified data

func (*Context) RespondWithError

func (c *Context) RespondWithError(err error, statusCode int) error

func (*Context) RespondWithErrorCode

func (c *Context) RespondWithErrorCode(statusCode int) error

Responds with the specified HTTP status code defined in RFC 2616 and adds the description to the errors list see http://golang.org/src/pkg/http/status.go for options

func (*Context) RespondWithErrorMessage

func (c *Context) RespondWithErrorMessage(message string, statusCode int) error

func (*Context) RespondWithLocation

func (c *Context) RespondWithLocation(location string) error

Responds with 302 Temporarily Moved (redirect)

func (*Context) RespondWithNotFound

func (c *Context) RespondWithNotFound() error

Responds with 404 Not Found

func (*Context) RespondWithNotImplemented

func (c *Context) RespondWithNotImplemented() error

Responds with 501 Not Implemented

func (*Context) RespondWithOK

func (c *Context) RespondWithOK() error

Responds with OK status (200) and no data

func (*Context) RespondWithRawData

func (c *Context) RespondWithRawData(data interface{}) error

Responds with the specified data

func (*Context) RespondWithStatus

func (c *Context) RespondWithStatus(statusCode int) error

Responds with the specified HTTP status code defined in RFC 2616 see http://golang.org/src/pkg/http/status.go for options

func (*Context) SignedCookie

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

Gets the cookie specified by name and validates that its value has not been tampered with by checking the signed cookie too. Will return CookieNotValid error if it has been tampered with, otherwise, it will return the actual cookie.

func (*Context) WriteResponse

func (c *Context) WriteResponse(obj interface{}, statusCode int) error

Writes the specified object out (with the specified status code) using the appropriate formatter

type Controller

type Controller interface {

	// When implemented, handles the request
	HandleRequest(c *Context)
}

Interface for controller types that handle requests

type ControllerFunc

type ControllerFunc func(*Context)

The ControllerFunc type is an adapter to allow the use of ordinary functions as goweb handlers. If f is a function with the appropriate signature, ControllerFunc(f) is a Controller object that calls f.

func (ControllerFunc) HandleRequest

func (f ControllerFunc) HandleRequest(c *Context)

HandleRequest calls f(c).

type FormRequestDecoder

type FormRequestDecoder struct{}

a form-enc decoder for request body

func (*FormRequestDecoder) Unmarshal

func (d *FormRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) error

type Formatter

type Formatter interface {
	// method to transform response
	Format(context *Context, input interface{}) ([]uint8, error)
	// method that decides if this formatter will be used
	Match(*Context) bool
	// init the formatter
	Init()
}

Interface describing an object responsible for handling transformed/formatted response data

func GetFormatter

func GetFormatter(cx *Context) (Formatter, error)

Gets the relevant formatter for the specified context or returns an error if no formatter is found

type GzipResponseWriter

type GzipResponseWriter struct {
	io.Writer
	http.ResponseWriter
}

func (GzipResponseWriter) Write

func (w GzipResponseWriter) Write(b []byte) (int, error)

type HttpHandler

type HttpHandler struct {
	IndexPath string
	// contains filtered or unexported fields
}

A handler type to handle actual http requests using the DefaultRouteManager to route requests to the right places

var DefaultHttpHandler *HttpHandler = &HttpHandler{routeManager: DefaultRouteManager, IndexPath: "/"}

The default http handler used to handle requests

func (*HttpHandler) GetMathingRoute

func (h *HttpHandler) GetMathingRoute(responseWriter http.ResponseWriter, request *http.Request) (bool, *Route, *Context)

Searches DefaultRouteManager to find the first matching route and returns it along with a boolean describing whether any routes were found or not, and the Context object built while searching for routes

func (*HttpHandler) HandleError

func (h *HttpHandler) HandleError(context *Context, err error)

Handles the specified error by passing it back to the user

func (*HttpHandler) ServeHTTP

func (handler *HttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request)

Serves the HTTP request and writes the response to the specified writer

type JsonFormatter

type JsonFormatter struct{}

Formatter for JSON

func (*JsonFormatter) Format

func (f *JsonFormatter) Format(cx *Context, input interface{}) ([]uint8, error)

Readies response and converts input data into JSON

func (*JsonFormatter) Init

func (f *JsonFormatter) Init()

func (*JsonFormatter) Match

func (f *JsonFormatter) Match(cx *Context) bool

Gets the "application/json" content type

type JsonRequestDecoder

type JsonRequestDecoder struct{}

a JSON decoder for request body (just a wrapper to json.Unmarshal)

func (*JsonRequestDecoder) Unmarshal

func (d *JsonRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) (err error)

type MobileRestHtmlFormattor

type MobileRestHtmlFormattor struct {
	RestHtmlFormattor
}

func (*MobileRestHtmlFormattor) Init

func (r *MobileRestHtmlFormattor) Init()

type MultiFormRequestDecoder

type MultiFormRequestDecoder struct{}

a form-enc decoder for request body

func (*MultiFormRequestDecoder) Unmarshal

func (d *MultiFormRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) error

type ParameterKeyMap

type ParameterKeyMap map[string]int

Holds parameter keys and their respective positions in the path

type ParameterValueMap

type ParameterValueMap map[string]string

Holds parameter keys and actual values

type RawFormatter

type RawFormatter struct{}

Formatter for JSON

func (*RawFormatter) Format

func (f *RawFormatter) Format(cx *Context, input interface{}) (output []uint8, err error)

Readies response and converts input data into JSON

func (*RawFormatter) Init

func (f *RawFormatter) Init()

func (*RawFormatter) Match

func (f *RawFormatter) Match(cx *Context) bool

Gets the "application/json" content type

type RequestDecoder

type RequestDecoder interface {
	Unmarshal(cx *Context, v interface{}, autofill bool) error
}

types that impliment RequestDecoder can unmarshal the request body into an apropriate type/struct

type RestContext

type RestContext struct {
	Url    string
	Method string
}

type RestController

type RestController interface{}

Interface for RESTful controllers

type RestCreator

type RestCreator interface {
	Create(c *Context)
}

Handler method to create a new item

type RestDeleter

type RestDeleter interface {
	Delete(id string, c *Context)
}

Handler method to delete an item specified by the ID

type RestEditor

type RestEditor interface {
	Edit(id string, c *Context)
}

Handler method to show the Edit page for item

type RestHtmlFormattor

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

Formatter for JSON

func (*RestHtmlFormattor) Format

func (f *RestHtmlFormattor) Format(cx *Context, input interface{}) ([]uint8, error)

Readies response and converts input data into JSON

func (*RestHtmlFormattor) Init

func (r *RestHtmlFormattor) Init()

func (*RestHtmlFormattor) Match

func (f *RestHtmlFormattor) Match(cx *Context) bool

Gets the "application/html" content type

type RestManyDeleter

type RestManyDeleter interface {
	DeleteMany(c *Context)
}

Handler method to delete a collection of items

type RestManyReader

type RestManyReader interface {
	ReadMany(c *Context)
}

Handler method to read many items

type RestManyUpdater

type RestManyUpdater interface {
	UpdateMany(c *Context)
}

Handler method to update many items

type RestModelTemplate

type RestModelTemplate struct {
	template.Template
}

type RestNewer

type RestNewer interface {
	New(c *Context)
}

Handler method to show the New page for item

type RestOptions

type RestOptions interface {
	Options(c *Context)
}

type RestReader

type RestReader interface {
	Read(id string, c *Context)
}

Handler method to read an item by the specified ID

type RestUpdater

type RestUpdater interface {
	Update(id string, c *Context)
}

Handler method to update a single item specified by the ID

type Route

type Route struct {
	Path         string
	Controller   Controller
	MatcherFuncs []RouteMatcherFunc
	// contains filtered or unexported fields
}

Represents a single route mapping

func Map

func Map(path string, controller Controller, matcherFuncs ...RouteMatcherFunc) *Route

Maps a new route to a controller (with optional RouteMatcherFuncs) and returns the new route

func MapFunc

func MapFunc(path string, controllerFunc func(*Context), matcherFuncs ...RouteMatcherFunc) *Route

Maps a new route to a function (with optional RouteMarcherFuncs) and returns the new route

func (*Route) DoesMatchContext

func (route *Route) DoesMatchContext(c *Context) bool

Checks whether the context for this request matches the route

func (*Route) DoesMatchPath

func (route *Route) DoesMatchPath(path string) bool

Checks whether a path matches a route or not

func (*Route) String

func (r *Route) String() string

type RouteManager

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

Manages routes and matching

var DefaultRouteManager *RouteManager = new(RouteManager)

Default instance of the RouteManager

func (*RouteManager) AddRoute

func (manager *RouteManager) AddRoute(route *Route)

Adds a route to the manager

func (*RouteManager) ClearRoutes

func (manager *RouteManager) ClearRoutes()

Clears all routes

func (*RouteManager) Map

func (manager *RouteManager) Map(path string, controller Controller, matcherFuncs ...RouteMatcherFunc) *Route

Creates a route that maps the specified path to the specified controller along with any optional RouteMatcherFunc modifiers

func (*RouteManager) MapFunc

func (manager *RouteManager) MapFunc(path string, contorllerFunction func(*Context), matcherFuncs ...RouteMatcherFunc) *Route

type RouteMatcherFunc

type RouteMatcherFunc func(c *Context) RouteMatcherFuncValue

Functions used to decide whether a route matches a request or not

type RouteMatcherFuncValue

type RouteMatcherFuncValue int

Represents the return value for RouteMatcher functions

const DontCare RouteMatcherFuncValue = -1

Indicates that the RouteMatcherFunc doesn't care whether the route is a Match or NoMatch

const Match RouteMatcherFuncValue = 1

Indicates that the route should match

const NoMatch RouteMatcherFuncValue = 0

Indicates that the route should NOT match

func DeleteMethod

func DeleteMethod(c *Context) RouteMatcherFuncValue

Returns Match if the Method of the http.Request in the specified Context is DELETE, otherwise returns DontCare

func GetMethod

func GetMethod(c *Context) RouteMatcherFuncValue

Returns Match if the Method of the http.Request in the specified Context is GET, otherwise returns DontCare

func OptionsMethod

func OptionsMethod(c *Context) RouteMatcherFuncValue

Returns Match if the Method of the http.Request in the specified Context is OPTIONS, otherwise returns DontCare

func PostMethod

func PostMethod(c *Context) RouteMatcherFuncValue

Returns Match if the Method of the http.Request in the specified Context is POST, otherwise returns DontCare

func PutMethod

func PutMethod(c *Context) RouteMatcherFuncValue

Returns Match if the Method of the http.Request in the specified Context is PUT, otherwise returns DontCare

type XmlRequestDecoder

type XmlRequestDecoder struct{}

an XML decoder for request body

func (*XmlRequestDecoder) Unmarshal

func (d *XmlRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) error

Jump to

Keyboard shortcuts

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