seven5

package
v0.0.0-...-e49eac2 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2015 License: MIT, MIT Imports: 24 Imported by: 0

README

# Seven5

An opinionated, stiff web framework written in Go

  • Seven5 is RESTful without remorse or pity.
  • Seven5 is fiercely reactionary towards the forces of dynamism.

Documentation

Index

Constants

View Source
const (
	REDIRECT_HOST_TEST = "http://localhost:%d"
	HEROKU_HOST        = "https://%s.herokuapp.com"
)
View Source
const (
	AUTH_OP_LOGIN         = "login"
	AUTH_OP_LOGOUT        = "logout"
	AUTH_OP_PWD_RESET     = "pwdreset"
	AUTH_OP_PWD_RESET_REQ = "pwdresetreq"
)
View Source
const (
	GOPATH_PREFIX = "/gopath"
	CONTINUE      = 50
)
View Source
const MAX_FORM_SIZE = 16 * 1024
View Source
const (
	SESSION_COOKIE = "%s-seven5-session"
)

Variables

View Source
var GOPHER_ICON = []byte{}/* 1150 elements not displayed */
View Source
var (
	NO_SUCH_COOKIE = errors.New("Cannot find cookie")
)

Functions

func GetDSNOrDie

func GetDSNOrDie() *qbs.DataSourceName

This function returns the datasource name for the DATABASE_URL in the environment. If the value cannot be found, this panics.

func GopathLookup

func GopathLookup(w http.ResponseWriter, r *http.Request, desired string)

Utility function for taking a requested URL and finding it in the Gopath and returning its contents. It will return 404 if the file cannot be found and expects that the desired parameter already has had the gopath prefix stripped of it, e.g. /foo.go not /gopath/foo.go.

func GopathSearch

func GopathSearch(desired string) string

Return the path to the file that has the desired content, or return "" if the file cannot be found.

func IsUDID

func IsUDID(s string) bool

func ParamsToDSN

func ParamsToDSN(dbname string, driver string, user string) *qbs.DataSourceName

ParamsToDSN allows you to create a DSN directly from some values. This is useful for testing. If driver or user is "", the default driver and user are used.

func ParseId

func ParseId(candidate string) (int64, string)

ParseId returns the id contained in a string or an error message about why the id is bad.

func SendJson

func SendJson(w http.ResponseWriter, i interface{}) error

Utility routine to send a json blob to the client side. Encoding errors are logged to the terminal and the client will recv a 500 error.

func StringToDialect

func StringToDialect(n string) qbs.Dialect

StringToDialect returns an sql dialect for use with QBS given a string name. IF the name is not known, this code panics.

func ToSimpleMap

func ToSimpleMap(m map[string][]string) map[string]string

ToSimpleMap converts an http level map with multiple strings as value to single string value. There are a number of places in HTTP (such as headers and query parameters) where this is possible and legal according to the spec, but still silly so we just use single valued values.

func UDID

func UDID() string

UDID returns a new UDID, formatted such that it wil pass IsUDID(), by reading /dev/urandom. This value contains 16 bytes of randomness.

func WriteError

func WriteError(w http.ResponseWriter, err error)

WriteError returns an error to the client side. If the err is of type Error, we decode the fields to produce the correct message and response code. Otherwise, we return the string of the error content plus the code http.StatusInternalServerError.

Types

type AllowReader

type AllowReader interface {
	AllowRead(PBundle) bool
}

AllowReader is an interface that allows a particular resource to express permissions about what users or types of requests are allowed on it. This is a good place to put gross-level kinds of "policy" decisions like "non staff members cannot call this method". This does not allow for very fine-grain policies about the _content_ of the returned values, such as "the list returned has all elements if the user is a staff member but only elements they own for normal users." AllowReader is used for the RestIndex interface. Return true to allow calls to RestIndex to be made with the PBundle provided.

type AllowWriter

type AllowWriter interface {
	AllowWrite(PBundle) bool
}

AllowWriter is an interface that allows a particular resource to express permissions about what users or types of requests are allowed on it. This is a good place to put gross-level kinds of "policy" decisions like "only staff members can create new instances of this resource". AllowWriter is used for the RestPost interface. Return true to allow calls to RestPost to be made with the PBundle provided.

type Allower

type Allower interface {
	Allow(int64, string, PBundle) bool
}

Allower is an interface that allows a particular resource to express permissions about what users or types of requests are allowed on it. This is a good place to put gross-level kinds of "policy" decisions like "users may only write to their to objects they own". Allower is used for RestFind, RestPut, or rest delete. The first parameter is the id of the resource. The second is the method of the request as as a string in uppercase, and the third is the parameter bundle that will be sent to the implementing method, if this method returns true.

type AllowerUdid

type AllowerUdid interface {
	Allow(string, string, PBundle) bool
}

AllowerUdid is an interface that allows a UDID resource to express permissions about what users or types of requests are allowed on it. This is a good place to put gross-level kinds of "policy" decisions like "users may only write to their to objects they own". Allower is used for RestFind, RestPut, or Rest Delete. The first parameter is the id of the resource. The second is the method of the request as as a string in uppercase, and the third is the parameter bundle that will be sent to the implementing method, if this method returns true.

type Authorizer

type Authorizer interface {
	Index(d *restShared, bundle PBundle) bool
	Post(d *restShared, bundle PBundle) bool
	Find(d *restObj, num int64, bundle PBundle) bool
	FindUdid(d *restObjUdid, id string, bundle PBundle) bool
	Put(d *restObj, num int64, bundle PBundle) bool
	PutUdid(d *restObjUdid, id string, bundle PBundle) bool
	Delete(d *restObj, num int64, bundle PBundle) bool
	DeleteUdid(d *restObjUdid, id string, bundle PBundle) bool
}

Authorizer is a type that allows implementors to control authorization and thus circumvent the usual rest dispatch machinery. This type is consumed by RawDispatcher and should only be implemented by other dispatchers. Applications should typically use the "Allow*" methods on their own resource implementation in combinations with the BaseDispatcher.

type BaseDispatcher

type BaseDispatcher struct {
	*RawDispatcher
}

BaseDispatcher is a slight "specialization" of the RawDispatcher for REST resources. BaseDispatcher understands how to dispatch to REST resources (like Raw) but can also handle the Allower protocol for primitive, coarse-grained authorization. Additionally, it allows easy creation of a BaseDispatcher with a custom SessionManager, as this is often used with user roles (and Allow protocol).

func NewBaseDispatcher

func NewBaseDispatcher(sm SessionManager, cm CookieMapper) *BaseDispatcher

NewBaseDispatcher returns a raw dispatcher that has several defaults set. * The Allow() interfaces are used for authorization checks * The application will keep a single cookie on the browser (that's why the cookie mapper is passed in) * The application will keep a session associated with the cookie for each "logged in" user (via the SessionManager) * Json is used to encode and decode the wire types * Rest resources dispatched by this object are mapped to /rest in the URL space. You must pass an already created session manager into this method (see NewSimpleSessionManager(...))

func (*BaseDispatcher) Delete

func (self *BaseDispatcher) Delete(d *restObj, num int64, bundle PBundle) bool

Find checks with Allower.Allow(DELETE) to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

func (*BaseDispatcher) DeleteUdid

func (self *BaseDispatcher) DeleteUdid(d *restObjUdid, id string, bundle PBundle) bool

Find checks with AllowerUdid.Allow(DELETE) to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

func (*BaseDispatcher) Find

func (self *BaseDispatcher) Find(d *restObj, num int64, bundle PBundle) bool

Find checks with Allower.Allow(FIND) to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

func (*BaseDispatcher) FindUdid

func (self *BaseDispatcher) FindUdid(d *restObjUdid, id string, bundle PBundle) bool

Find checks with Allower.AllowUdid(GET) to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

func (*BaseDispatcher) Index

func (self *BaseDispatcher) Index(d *restShared, bundle PBundle) bool

Index checks with AllowReader.AllowRead to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

func (*BaseDispatcher) Post

func (self *BaseDispatcher) Post(d *restShared, bundle PBundle) bool

Post checks with AllowWriter.AllowWrite to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

func (*BaseDispatcher) Put

func (self *BaseDispatcher) Put(d *restObj, num int64, bundle PBundle) bool

Put checks with Allower.Allow(PUT) to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

func (*BaseDispatcher) PutUdid

func (self *BaseDispatcher) PutUdid(d *restObjUdid, id string, bundle PBundle) bool

Put checks with Allower.AllowUdid(PUT) to allow/refuse access to this method on _any_ resource associated with this BaseDispatcher.

type ComponentMatcher

type ComponentMatcher interface {
	http.Handler
	FormFilepath(lang, ui, path string) string
	Match(pb PBundle, path string) ComponentResult
}

ComponentMatcher takes a requested URL and converts it to a static filename. Because the semantics of the transformation may involve things other than URL path (such as current session), Match is called with the fully constructed PBundle. Note that this processing (in Match) usually stateless in that the _exact_ URL is typically not checked; a request for /foo/123 might result in the static file /foo/view.html even though no foo exists with id 123.

type ComponentResult

type ComponentResult struct {
	Status           int
	ContinueAt       string //only used if Status = CONTNUE
	ContinueConsumed int    //only used if Status = CONTINUE
	Message          string //only used if non 200s
	Redir            string //only used if status is 301
	Path             string //only used if 200
}

ComponentResult is produced when we try to match a URL provided by the client to a fixed file. If the Status is 200, then server should *try* to serve the file at Path. Note that this file may not exists and the final result would thus be a 404 back to the client. If the status is 301 (MovedPermanently) the url (path) given by Redir is sent to client. If the Status is CONTINUE the processing of the URL can continue. This continuation allows for part of the URL to be consumed by one component while allowing other components to still receive the later portions. If the Status is anything else, it is sent to the client, along with the Message.

type CookieMapper

type CookieMapper interface {
	CookieName() string
	Value(*http.Request) (string, error)
	AssociateCookie(http.ResponseWriter, Session)
	RemoveCookie(http.ResponseWriter)
}

CookieMapper mediates the interaction between requests and cookies. Most applications probably want to implement the SessionManager not the CookieMapper. CookieMapper is primarily of interest for those who need to interact with the Set-Cookie and Cookie headers from/to the browser.

func NewSimpleCookieMapper

func NewSimpleCookieMapper(appName string) CookieMapper

NewSimpleCookieMapper creates an instance of CookieMapper with the given application name.

type Decoder

type Decoder interface {
	Decode([]byte, interface{}) error
}

type DeploymentEnvironment

type DeploymentEnvironment interface {
	//GetQbsStore returns the correct flavor of QbsStore for the deployment
	//environment, taking into account possible test settings.
	GetQbsStore() *QbsStore
	//IsTest returns true if this application is running on
	//a local system, not deployed to remote system.
	IsTest() bool
	//Returns the port number for this application.
	Port() int
	//RedirectHost is needed in cases where you are using oauth because this must sent to the
	//"other side" of the handshake without any extra knowlege.
	RedirectHost() string
}

DeploymentEnvironment encodes information that cannot be obtained from the source code but can only be determined from "outside" the application. This is here to provide a a vague hope of supporting deployments that are not based on environment variables.

type Dispatcher

type Dispatcher interface {
	Dispatch(*ServeMux, http.ResponseWriter, *http.Request) *ServeMux
}

Dispatcher is the low-level interface to requests and responses. Most user level code should not need to implement Dispatchers but rather should choose one or more dispatchers to "install" in their application. A dispatcher may return an instance of ServeMux (possibly the same one passed to it as the first parameter) if it wants the processing of the request to continue after it executes; this allows Dispatchers that wrap the entire url space.

type Encoder

type Encoder interface {
	Encode(wireType interface{}, prettyPrint bool) (string, error)
}

type ErrWrapper

type ErrWrapper struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ErrWrapper is a wrapper around http.ResponseWriter that holds enough state to call its held ErrorDispatcher in case of an error status code being written.

func (*ErrWrapper) WriteHeader

func (self *ErrWrapper) WriteHeader(status int)

WriteHeader is a wrapper around the http.ResponseWriter method of the same name. It simply traps status code writes of 300 or greater and calls the error dispatcher to handle it.

type Error

type Error struct {
	StatusCode int
	Msg        string
}

Error is a type that can be used by a resource that wants to send a particular HTTP response back to the client. If a resource returns any error _other_ than this one, it is considered an internal server error. This should not be used to return 200 "OK" results, use nil instead.

func HTTPError

func HTTPError(code int, msg string) *Error

func (*Error) Error

func (self *Error) Error() string

error() makes this an implementation of the type error

type ErrorDispatcher

type ErrorDispatcher interface {
	ErrorDispatch(int, http.ResponseWriter, *http.Request)
	PanicDispatch(interface{}, http.ResponseWriter, *http.Request)
}

ErrorDispatcher is a special case of dispatcher that is only invoked when other Dispatchers return some type of error condition. An "error" is defined as an http response code greater than 300 or a panic. The original response writer and request are passed to the ErrorDispatch() method to allow the error dispatcher to take any action desired. An error dispatcher that does nothing will implicitly allow whatever calls the other dispatcher placed on the response writer to proceed. ErrorDispatcher is also called when no dispatcher is found (404).

type ExistsCheck

type ExistsCheck func(pb PBundle, id int64) (bool, error)

ExistsCheck is a function that is called by SimpleComponentMatcher to test if a given id is valid. It should return false, error in case of an error false,nil to indicate the id was not found and true, nil to indicate that processing can continue.

type Generator

type Generator interface {
	Generate(uniqueInfo string) (interface{}, error)
}

Generator is a type that converts from a small amount of unique info to the data that should be stored in a session. It is called when an http request is received (see IOHook) and the user has previously visited this website. The uniqueInfo provide is recovered from the session id, typically using the SERVER_SESSION_KEY for decryption, so it cannot be forged if this type is used with SimpleSessionManager. The value returned will be associated with a newly created session and http processing will continue. If an error is returned, it should be one created with s5.HttpError() to provide a correct HTTP status code and message to the client.

type HerokuDeploy

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

HerokuDeploy is an implementation of DeploymentEnvironment that understands about Heroku and reads its configuration from environment variables.

func NewHerokuDeploy

func NewHerokuDeploy(herokuName string, appName string) *HerokuDeploy

NewHerokuDeploy returns a new HerokuDeploy object that implements DeploymentEnvironment. The first parameter is the _host_ name on heroku, typically like damp-sierra-7161. The second parameter is the application's name locally, like myproject.

func (*HerokuDeploy) GetQbsStore

func (self *HerokuDeploy) GetQbsStore() *QbsStore

GetQbsStore returns a Qbs store suitable for use with tihs application. The implementation uses GetDSNOrDie which ends up looking for the environment variable DATABASE_URL which must be set or we panic.

func (*HerokuDeploy) IsTest

func (self *HerokuDeploy) IsTest() bool

IsTest returns true if the environment variable localname_TEST is set to a value that's not "".

func (*HerokuDeploy) Port

func (self *HerokuDeploy) Port() int

Port reads the value of the environment variable PORT to get the value to return here. It will panic if the environment variable is not set or it's not a number.

func (*HerokuDeploy) RedirectHost

func (self *HerokuDeploy) RedirectHost() string

RedirectHost is needed in cases where you are using oauth because this must sent to the "other side" of the handshake without any extra knowlege.

func (*HerokuDeploy) Url

func (self *HerokuDeploy) Url() string

Url returns the string that points to the application itself. Note that this will not have a / on the end.

type IOHook

type IOHook interface {
	SendHook(d *restShared, w http.ResponseWriter, pb PBundle, i interface{}, location string)
	BundleHook(w http.ResponseWriter, r *http.Request, sm SessionManager) (PBundle, error)
	BodyHook(r *http.Request, obj *restShared) (interface{}, error)
	CookieMapper() CookieMapper
}

IOHook is an interface provided as a convenience to those who want to override the behavior of some aspect of reading and writing web content. This can be used to change the format of http input/output (such as ignoring parts of the body content, changing how cookies are used, etc) or to change the parameters passed to rest resources in the PBundle (for example to modify query parameter arguments programmatically).

type IndexOnlyComponent

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

IndexOnlyComponent returns the page /plural/index.html for the requested url /plural, /plural/, or /plural/index.html. Note that this can still 404 if the actual file is not present.

func NewIndexOnlyComponent

func NewIndexOnlyComponent(plural string, path string) *IndexOnlyComponent

NewIndexOnlyComponent returns a StaticComponent that understands exacly three urls. The urls understood is /plural, /plural/, and /plural/index.html and all of these return the file provided in path. For convenience, it is often useful to map /plural/index.html to /singular/index.html so that all the files for a given type are in the same directory, rather than having a single file in the plural directory.

func (*IndexOnlyComponent) Page

func (self *IndexOnlyComponent) Page(pb PBundle, path []string, trailingSlash bool) ComponentResult

Page does the work of turning a path plus a PBundle into a ComponentResult. That ComponentResult might have Status==CONTINUE for a url like /plural/index.css.

func (*IndexOnlyComponent) UrlPrefix

func (self *IndexOnlyComponent) UrlPrefix() string

type JsonDecoder

type JsonDecoder struct {
}

func (*JsonDecoder) Decode

func (self *JsonDecoder) Decode(body []byte, wireType interface{}) error

Decode is called to turn a body supplied by the client into an object of the appropriate wire type. Note that the interface{} passed here _must_ be pointer.

type JsonEncoder

type JsonEncoder struct {
}

func (*JsonEncoder) Encode

func (self *JsonEncoder) Encode(wireType interface{}, prettyPrint bool) (string, error)

type NewCheck

type NewCheck func(pb PBundle) (bool, error)

NewCheck is a function that is called by SimpleComponentMatcher if it is acceptable to allow the current user to view the page /singular/new or /singluar/new.html. Like ViewEditCheck, this function should return errors in the second parameter and true in the first parameter only if it is ok to continue processing.

type OauthClientDetail

type OauthClientDetail interface {
	ClientId(serviceName string) string
	ClientSecret(serviceName string) string
}

OauthClientDetail is an interface for finding the specific information needed to connect to an Oauth server. If you don't want to use environment variables as the way you store these, you can provide your own implementation of this class.

type OauthConnection

type OauthConnection interface {
	//Note that we don't want to expose an http.Client because oauth1 wants to do this
	//in a simple way of adding a single header to the output.
	SendAuthenticated(*http.Request) (*http.Response, error)
}

OauthConnection is a per-client connection to the service that the connection was returned from. Its only method is the same as "http.Client.Do()" but with specific authentication machinery for the connector. Note that there are failures of the authentication machinery and http failures lumped together on the error return value.

type OauthConnector

type OauthConnector interface {
	ClientTokenValueName() string
	CodeValueName() string
	ErrorValueName() string
	StateValueName() string
	//Phase is not used by Oauth2 so it returns nil for OauthCred
	Phase1(state string, callbackPath string) (OauthCred, error)
	//Both versions use the state passed in here to help you know what to do when
	//you land on the login page
	UserInteractionURL(p1creds OauthCred, state string, callbackPath string) string
	//Oauth2 client token?
	Phase2(clientToken string, code string) (OauthConnection, error)
	Name() string
}

OauthConnector is an abstraction of a service that can do Oauth-based authentication. This abstraction papers over, badly, the differences between oauth2 and oauth1(a).

type OauthCred

type OauthCred interface {
	Token() string
	Secret() string
}

type PBundle

type PBundle interface {
	Header(string) (string, bool)
	Query(string) (string, bool)
	Session() Session
	ReturnHeader(string) string
	SetReturnHeader(string, string)
	ReturnHeaders() []string
	UpdateSession(interface{}) (Session, error)
	DestroySession() error
	ParentValue(interface{}) interface{}
	SetParentValue(reflect.Type, interface{})
	IntQueryParameter(string, int64) int64
}

func NewSimplePBundle

func NewSimplePBundle(r *http.Request, s Session, mgr SessionManager) (PBundle, error)

NewSimplePBundle needs to hold a reference to the session manager as well as the session because it must be able to update the information stored about a particular sesison.

func NewTestPBundle

func NewTestPBundle(headers map[string]string, query map[string]string, session Session,
	mgr SessionManager, output map[string]string, parent map[reflect.Type]interface{}) PBundle

NewTestPBundle makes a Pbundle from the given constants. Note that you can supply a session manager of nil and the consumer of this object doesn't try to update the current session, this is ok.

type PageMapper

type PageMapper interface {
	ErrorPage(OauthConnector, string) string
	LoginLandingPage(OauthConnector, string, string) string
	LogoutLandingPage(OauthConnector) string
}

PageMapper is an interface for expressing the "landing" pages for a particular action in the user application. These are part of the application. This is necessary because this must be handled programmatically by the back end and can't necessarily use files. Note that the ErrorPage receives a parameter which is the error text and the login page receives both the state parameter and the code (via oauth) that was received on successfully getting an oauth token. These functions should return a URL as a string.

type PagegenOpts

type PagegenOpts struct {
	Funcs           map[string]interface{} //but they better be funcs
	BaseDir         string                 //normally cmd line opt
	SupportDir      string                 //normally cmd line opt
	JsonSupportFile string
	JsonFile        string
	TemplateFile    string
	Debug           bool
	TemplateSuffix  string
}

func (PagegenOpts) Main

func (po PagegenOpts) Main()

type PasswordAuthParameters

type PasswordAuthParameters struct {
	Username         string
	Password         string
	ResetRequestUdid string
	UserUdid         string
	Op               string
}

PasswordAuthParameters is passed from client to server to request login, login or to use (consume) a reset request. XXX Ugh, this has to be manually copied over to the client side library. XXX

type QbsDefaultOrmTransactionPolicy

type QbsDefaultOrmTransactionPolicy struct {
}

QbsDefaultOrmTransactionPolicy is a simple implementation of transaction policy that is sufficient for most applications.

func NewQbsDefaultOrmTransactionPolicy

func NewQbsDefaultOrmTransactionPolicy() *QbsDefaultOrmTransactionPolicy

NewQbsDefaultOrmTransactionPolicy returns a new default implementation of policy that will Rollback transactions if there is a 400 or 500 returned by the client. It will also rollback if a non-http error is returned, or if the called code panics. After rolling back the transaction, it allows the panic to continue.

func (*QbsDefaultOrmTransactionPolicy) HandlePanic

func (self *QbsDefaultOrmTransactionPolicy) HandlePanic(tx *qbs.Qbs, err interface{}) (interface{}, error)

HandlePanic rolls back the transiction provided and then panics again.

func (*QbsDefaultOrmTransactionPolicy) HandleResult

func (self *QbsDefaultOrmTransactionPolicy) HandleResult(tx *qbs.Qbs, value interface{}, err error) (interface{}, error)

HandleResult determines whether or not the transaction provided should be rolled back or if it should be committed. It rolls back when the result value is a non-http error, if it is an Error and the status code is >= 400.

func (*QbsDefaultOrmTransactionPolicy) StartTransaction

func (self *QbsDefaultOrmTransactionPolicy) StartTransaction(q *qbs.Qbs) *qbs.Qbs

StartTransaction returns a new qbs object after creating the transaction.

type QbsRestAll

QbsRestAll is the same as RestAll but with the additional qbs.Qbs parameter on each method.

type QbsRestAllUdid

QbsRestAllUdid is the same as RestAllUdid but with the additional qbs.Qbs parameter on each method.

type QbsRestDelete

type QbsRestDelete interface {
	DeleteQbs(int64, PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestDelete is the QBS version of RestDelete

type QbsRestDeleteUdid

type QbsRestDeleteUdid interface {
	DeleteQbs(string, PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestDeleteUdid is the QBS version of RestDeleteUdid

type QbsRestFind

type QbsRestFind interface {
	FindQbs(int64, PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestFind is the QBS version of RestFind

type QbsRestFindUdid

type QbsRestFindUdid interface {
	FindQbs(string, PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestFindUdid is the QBS version of RestFindUdid

type QbsRestIndex

type QbsRestIndex interface {
	IndexQbs(PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestIndex is the QBS version of RestIndex

type QbsRestPost

type QbsRestPost interface {
	PostQbs(interface{}, PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestPost is the QBS version RestPost

type QbsRestPut

type QbsRestPut interface {
	PutQbs(int64, interface{}, PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestPut is the QBS version RestPut

type QbsRestPutUdid

type QbsRestPutUdid interface {
	PutQbs(string, interface{}, PBundle, *qbs.Qbs) (interface{}, error)
}

QbsRestPut is the QBS version RestPutUdid

type QbsStore

type QbsStore struct {
	Policy *QbsDefaultOrmTransactionPolicy
	Dsn    *qbs.DataSourceName
}

func NewQbsStoreFromDSN

func NewQbsStoreFromDSN(dsn *qbs.DataSourceName) *QbsStore

NewQbsStoreFromDSN creates a *QbsStore from a DSN; DSNs can be created directly with ParamsToDSN or from the environment with GetDSNOrDie, via the DATABASE_URL environment var.

type RawDispatcher

type RawDispatcher struct {
	Root       *RestNode
	IO         IOHook
	SessionMgr SessionManager
	Auth       Authorizer
	Prefix     string
}

RawDispatcher is the "parent" type of dispatchers that understand REST. This class is actually broken into pieces so that parts of its implementation may be changed by applications.

func NewRawDispatcher

func NewRawDispatcher(io IOHook, sm SessionManager, a Authorizer, prefix string) *RawDispatcher

NewRawDispatcher is the lower-level interface to creating a RawDispatcher. Applications only need this function if they wish to substitute their own implementation for some portion of the handling of rest resources. The prefix is used to tell the dispatcher where it is mounted so it can "strip" this prefix from any URL paths it is decoding. This should be "" if the dispatcher is mounted at /; it should not end in a / or the entire world will come to a fiery end.

func (*RawDispatcher) AddResourceSeparate

func (self *RawDispatcher) AddResourceSeparate(node *RestNode, name string, wireExample interface{}, index RestIndex,
	find RestFind, post RestPost, put RestPut, del RestDelete)

AddResourceSeparate adds a resource to a given rest node, in a way parallel to ResourceSeparate.

func (*RawDispatcher) AddResourceSeparateUdid

func (self *RawDispatcher) AddResourceSeparateUdid(node *RestNode, name string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid)

AddResourceSeparateUdid adds a resource to a given rest node, in a way parallel to ResourceSeparateUdid.

func (*RawDispatcher) Dispatch

func (self *RawDispatcher) Dispatch(mux *ServeMux, w http.ResponseWriter, r *http.Request) *ServeMux

Dispatch is the entry point for the dispatcher. Most types will want to leave this method intact (don't override) and instead override particular hooks to add/modify particular functionality.

func (*RawDispatcher) DispatchSegment

func (self *RawDispatcher) DispatchSegment(mux *ServeMux, w http.ResponseWriter, r *http.Request,
	parts []string, current *RestNode, bundle PBundle)

DispatchSegment is responsible for taking a part of the url, starting from the left and breaking it into segments for processing. This is called by Dispatch() to initiate processing at the top level of resources but will be called recursively during dispatch processing.

func (*RawDispatcher) FindWireType

func (self *RawDispatcher) FindWireType(target reflect.Type, curr *RestNode) *RestNode

FindWireType searches the tree of rest resources trying to find one that has the given type as a target. This is only of interest to dispatch implementors.

func (*RawDispatcher) Resource

func (self *RawDispatcher) Resource(name string, wireExample interface{}, r RestAll)

Resource is the shorter form of ResourceSeparate that allows you to pass a single resource in so long as it meets the interface RestAll. Resource name must be singular and camel case and will be converted to all lowercase for use as a url. The example wire type's fields must be public.

func (*RawDispatcher) ResourceSeparate

func (self *RawDispatcher) ResourceSeparate(name string, wireExample interface{}, index RestIndex,
	find RestFind, post RestPost, put RestPut, del RestDelete)

ResourceSeparate adds a resource type to this dispatcher with each of the Rest methods individually specified. The name should be singular and camel case. The example should an example of the wire type to be marshalled, unmarshalled. This is just a wrapper around adding a resource at the top (root) level of the dispatcher with AddResourceSeparate.

func (*RawDispatcher) ResourceSeparateUdid

func (self *RawDispatcher) ResourceSeparateUdid(name string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid)

ResourceSeparateUdid adds a resource type to this dispatcher with each of the RestUdid methods individually specified. The name should be singular and camel case. The example should an example of the wire type to be marshalled, unmarshalled. The wire type can have an Id in addition to a Udid field.

func (*RawDispatcher) ResourceUdid

func (self *RawDispatcher) ResourceUdid(name string, wireExample interface{}, r RestAllUdid)

ResourceUdid is the shorter form of ResourceSeparateUdid that allows you to pass a single resource in so long as it meets the interface RestAllUdid. Resource name must be singular and camel case and will be converted to all lowercase for use as a url. The example wire type's fields must be public.

func (*RawDispatcher) Rez

func (self *RawDispatcher) Rez(wireExample interface{}, r RestAll)

Rez is the really short form for adding a resource. It assumes that the name is the same as the wire type and that the resource supports RestAll.

func (*RawDispatcher) RezUdid

func (self *RawDispatcher) RezUdid(wireExample interface{}, r RestAllUdid)

RezUdid is the really short form for adding a resource based on Udid. It assumes that the name is the same as the wire type and that the resource supports RestAllUdid.

func (*RawDispatcher) SendError

func (self *RawDispatcher) SendError(err error, w http.ResponseWriter, msg string)

func (*RawDispatcher) SubResource

func (self *RawDispatcher) SubResource(parentWire interface{},
	subresourcename string, wireExample interface{}, index RestIndex, find RestFind, post RestPost, put RestPut, del RestDelete)

SubResource is for adding a subresource, analagous to Resource You must provide the name of the wire type, lower case and singular, to be used with this resource. This call panics if the provided parent wire example cannot be located because this indicates that the program is misconfigured and cannot work.

func (*RawDispatcher) SubResourceSeparate

func (self *RawDispatcher) SubResourceSeparate(parentWire interface{}, wireExample interface{}, index RestIndex,
	find RestFind, post RestPost, put RestPut, del RestDelete)

SubResourceSeparate is for adding a subresource, analagous to ResourceSeparate. It assumes that the subresource name is the same as the wire type. This call panics if the provided parent wire example cannot be located because this indicates that the program is misconfigured and cannot work.

func (*RawDispatcher) SubResourceSeparateUdid

func (self *RawDispatcher) SubResourceSeparateUdid(parentWire interface{}, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid)

SubResourceSeparateUdid is for adding a subresource udid, analagous to ResourceSeparateUdid. It assumes that the subresource name is the same as the wire type. If the provided parent wire example cannot be located because this indicates that the program is misconfigured and cannot work.

func (*RawDispatcher) SubResourceUdid

func (self *RawDispatcher) SubResourceUdid(parentWire interface{}, subresourcename string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid)

SubResourceUdid is for adding a subresource udid, analagous to ResourceUdid. You must provide the subresource name, singular and lower case. If the provided parent wire example cannot be located because this indicates that the program is misconfigured and cannot work.

type RawIOHook

type RawIOHook struct {
	Dec       Decoder
	Enc       Encoder
	CookieMap CookieMapper
}

RawIOHook is the default implementation of the IOHook used by the RawDispatcher.

func NewRawIOHook

func NewRawIOHook(d Decoder, e Encoder, c CookieMapper) *RawIOHook

NewRawIOHook returns a new RawIOHook ptr with the decoder and encoder provided. This object needs a cookie mapper because setting and reading cookies is IO to the client! You can provided your own encoder and decoder pair if you wish to just change the format of the encoding used when marshalling and unmarshalling wire types (from json to xml, for example).

func (*RawIOHook) BodyHook

func (self *RawIOHook) BodyHook(r *http.Request, obj *restShared) (interface{}, error)

BodyHook is called to create a wire object of the appopriate type and fill in the values in that object from the request body. BodyHook calls the decoder provided at creation time take the bytes provided by the body and initialize the object that is ultimately returned.

func (*RawIOHook) BundleHook

func (self *RawIOHook) BundleHook(w http.ResponseWriter, r *http.Request, sm SessionManager) (PBundle, error)

BundleHook is called to create the bundle of parameters from the request. It often will be using cookies and sessions to compute the bundle. Note that the ResponseWriter is passed here but the BundleHook _must_ be careful to not force it out the server--it should only add headers. Note that the session manager may receive a call back if the consumer of the pbundle does Update().

func (*RawIOHook) CookieMapper

func (self *RawIOHook) CookieMapper() CookieMapper

CookieMapper is exposed because other parts of the system may need access to the cookie mapper to allow them to manipulate cookies. This allows centralization of all cookie handling in one type.

func (*RawIOHook) SendHook

func (self *RawIOHook) SendHook(d *restShared, w http.ResponseWriter, pb PBundle, i interface{}, location string)

SendHook is called to encode and write the object provided onto the output via the response writer. The last parameter if not "" is assumed to be a location header. If the location parameter is provided, then the response code is "Created" otherwise "OK" is returned. SendHook calls the encoder for the encoding of the object into a sequence of bytes for transmission. If the pb is not null, then the SendHook should examine it for outgoing headers, trailers, and transmit them.

type RestAll

type RestAll interface {
	RestIndex
	RestFind
	RestDelete
	RestPost
	RestPut
}

func QbsWrapAll

func QbsWrapAll(a QbsRestAll, s *QbsStore) RestAll

Given a QbsRestAll return a RestAll

type RestAllUdid

type RestAllUdid interface {
	RestIndex
	RestFindUdid
	RestDeleteUdid
	RestPost
	RestPutUdid
}

func QbsWrapAllUdid

func QbsWrapAllUdid(a QbsRestAllUdid, s *QbsStore) RestAllUdid

Given a QbsRestAllUdid return a RestAllUdid

type RestDelete

type RestDelete interface {
	Delete(int64, PBundle) (interface{}, error)
}

func QbsWrapDelete

func QbsWrapDelete(deler QbsRestDelete, s *QbsStore) RestDelete

Given a QbsRestDelete return a RestDelete

type RestDeleteUdid

type RestDeleteUdid interface {
	Delete(string, PBundle) (interface{}, error)
}

func QbsWrapDeleteUdid

func QbsWrapDeleteUdid(deler QbsRestDeleteUdid, s *QbsStore) RestDeleteUdid

Given a QbsRestDeleteUdid return a RestDeleteUdid

type RestFind

type RestFind interface {
	Find(int64, PBundle) (interface{}, error)
}

func QbsWrapFind

func QbsWrapFind(finder QbsRestFind, s *QbsStore) RestFind

Given a QbsRestFind return a RestFind

type RestFindUdid

type RestFindUdid interface {
	Find(string, PBundle) (interface{}, error)
}

func QbsWrapFindUdid

func QbsWrapFindUdid(finder QbsRestFindUdid, s *QbsStore) RestFindUdid

Given a QbsRestFindUdid return a RestFindUdid

type RestIndex

type RestIndex interface {
	Index(PBundle) (interface{}, error)
}

func QbsWrapIndex

func QbsWrapIndex(indexer QbsRestIndex, s *QbsStore) RestIndex

Given a QBSRestIndex return a RestIndex

type RestNode

type RestNode struct {
	Res          map[string]*restObj
	ResUdid      map[string]*restObjUdid
	Children     map[string]*RestNode
	ChildrenUdid map[string]*RestNode
}

RestNodes are tree nodes in the tree of rest resources. A RestNode encodes all the items that are directly reachable from this point. This type is not of interest to those not implementing their own dispatching.

func NewRestNode

func NewRestNode() *RestNode

NewRestNode creates a new, empty rest node.

type RestPost

type RestPost interface {
	Post(interface{}, PBundle) (interface{}, error)
}

func QbsWrapPost

func QbsWrapPost(poster QbsRestPost, s *QbsStore) RestPost

Given a QbsRestPost return a RestPost

type RestPut

type RestPut interface {
	Put(int64, interface{}, PBundle) (interface{}, error)
}

func QbsWrapPut

func QbsWrapPut(puter QbsRestPut, s *QbsStore) RestPut

Given a QbsRestPut return a RestPut

type RestPutUdid

type RestPutUdid interface {
	Put(string, interface{}, PBundle) (interface{}, error)
}

func QbsWrapPutUdid

func QbsWrapPutUdid(puter QbsRestPutUdid, s *QbsStore) RestPutUdid

Given a QbsRestPut return a RestPut

type ServeMux

type ServeMux struct {
	*http.ServeMux
	// contains filtered or unexported fields
}

ServeMux is drop in replacement for http.ServeMux that implements the Seven5 dispatch protocol on top of the existing "handler" abstraction in the net/http package.

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux creates a new server mux (compatible with http.ServeMux) with the specified error handler, which may be nil.

func (*ServeMux) Dispatch

func (self *ServeMux) Dispatch(pattern string, dispatcher Dispatcher)

Dispatch has the same function as "HandleFunc" on an http.ServeMux with the exception that we require the Dispatcher interface rather than a "HandleFunc" function.

func (*ServeMux) ErrorDispatcher

func (self *ServeMux) ErrorDispatcher() ErrorDispatcher

func (*ServeMux) ServeHTTP

func (self *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is a simple wrapper around the http.ServeMux method of the same name that incorporates an error wrapper to allow it to implement the ErrorDispatcher protocol.

func (*ServeMux) SetErrorDispatcher

func (self *ServeMux) SetErrorDispatcher(e ErrorDispatcher)

type Session

type Session interface {
	SessionId() string
	UserData() interface{}
}

Session is the minimal interface to a session. Most applications should not need to implement this type and can use the SimpleSession object.

type SessionManager

type SessionManager interface {
	Assign(id string, ud interface{}, expires time.Time) (Session, error)
	Find(id string) (*SessionReturn, error)
	Destroy(id string) error
	Update(Session, interface{}) (Session, error)
	Generate(string) (interface{}, error)
}

SessionManager is a type that most applications should not need to implement. It handles the particular session semantics in connection with the establishment of user sessions and mapping browser cookies to sessions. SessionManager implementations _must_ be safe to be accessed from multiple goroutines. Because the SessionManager can be accessed a via the pbundle interface, there will be multiple goroutines handling requests that could call through this interface. The SimpleSessionManager implentation has this property and may be a useful model for other implementors.

type SessionReturn

type SessionReturn struct {
	Session  Session
	UniqueId string
}

SessionReturn is returned from a call to Find. It contains either a Session or a unique id, never both. The uniqueId will be the one recovered from the cookie that was originally passed to Assign(), although perhaps not on this run of the program. When Find() returns nil, then there was either no session data to recover or the session expired, keys changed or some other event that means you better re-check the user.

type SimpleComponentMatcher

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

SimpleComponentMatcher is an implementation of a ComponentMatcher that serves us static files from a specific directory.

func NewSimpleComponentMatcher

func NewSimpleComponentMatcher(cm CookieMapper, sm SessionManager, basedir string,
	emptyURLHandler ComponentResult, isTest bool, comp ...StaticComponent) *SimpleComponentMatcher

NewSimpleComponentMatcher takes any number of StaticComponent objects and uses these to parse the URLs provided. When a URL is successfully parsed it returns a static file from basedir (or a 404 if its not there). The CookieMapper and SessionManager are needed because some StaticComponents need to have the full PBundle to do their work--and thus we must be able to decode the current session from cookies sent by the browser. If isTest is true we will also attempt to serve content from the GOPATH to allow more convenient debugging in a browser. The emptyURLHandler is used as the result of the user requesting the url "/".

func (*SimpleComponentMatcher) AddComponents

func (c *SimpleComponentMatcher) AddComponents(sc ...StaticComponent)

AddComponent adds any number of StaticComponents to this matcher.

func (*SimpleComponentMatcher) FormFilepath

func (c *SimpleComponentMatcher) FormFilepath(lang, ui, path string) string

FormFilepath is used to convert a url like "/foo/123/view.html" into "/en/web/foo/123/view.html" for processing in the filesystem. If the lang and ui are already present in the path, such as /fr/mobile/foo/123/view.html, they are honored and the url is not changed. Otherwise we join the lang and ui onto the front of the path before servicing the request for a file.

func (*SimpleComponentMatcher) Match

Match takes in a path and a PBundle, derived from a client request, and returns a ComponentResult which will be either a redirect, a path to a file (that may or may not exist), or some other error. Note that this return value never has Status==CONTINUE because that is only used during the internal processing inside this function.

func (*SimpleComponentMatcher) ServeHTTP

func (self *SimpleComponentMatcher) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP makes SimpleComponentMatcher meet the interface http.Handler.

type SimpleCookieMapper

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

SimpleCookieMapper is a default, cookie mapper that maps UDID strings to Session objects and uses a simple cookie scheme to extract the UDIDs from requests generated by the browser.

func (*SimpleCookieMapper) AssociateCookie

func (self *SimpleCookieMapper) AssociateCookie(w http.ResponseWriter, s Session)

AssociateCookie is used to effectively "Log in" a particular user by associating a session with a response w that will be sent back to their browser.

func (*SimpleCookieMapper) CookieName

func (self *SimpleCookieMapper) CookieName() string

CookieName returns the name of the cookie used for this application by this session manager.

func (*SimpleCookieMapper) RemoveCookie

func (self *SimpleCookieMapper) RemoveCookie(w http.ResponseWriter)

RemoveCookie is used to effectively "Log out" a particular user by removing the association of a session with a response w that will be sent back to their browser.

func (*SimpleCookieMapper) Value

func (self *SimpleCookieMapper) Value(r *http.Request) (string, error)

Value returns the cookie value associated with a given request or an error if that cookie is not present. Usually the value is the UDID of the session.

type SimpleIdComponent

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

SimpleIdComponent is designed to allow urls like /foo/1 to work. IdComponent serves the static file /foo/view.html for the requested urls of the form /foo/123,/foo/123/, and /foo/123/view.html. If the user has a current session and is an admin urls like /foo/123/edit will resolve to the file /foo/edit.html. Given a url of the form /foo/ it will try to serve /foo/index.html, but this (or any of the resulting files) can result in a 404 when trying to serve the static content.

func NewSimpleIdComponent

func NewSimpleIdComponent(singular string, exists ExistsCheck, newcheck NewCheck, viewedit ViewEditCheck) *SimpleIdComponent

NewSimpleIdComponent creates a simple id (int64 type) based implementation of StaticComponent. The caller may choose to provide either or both of the check functions to do access control during URL evaluation. The url's processed are of the form /singular/123. If any of the check functions are not supplied it is assumed that access is ok (and it can still be disallowed in the rest apis later).

func (*SimpleIdComponent) Page

func (self *SimpleIdComponent) Page(pb PBundle, path []string, trailingSlash bool) ComponentResult

Page does the work of turning a path plus a PBundle into a ComponentResult. That ComponentResult might have Status==CONTINUE.

func (*SimpleIdComponent) UrlPrefix

func (self *SimpleIdComponent) UrlPrefix() string

type SimpleOauthCred

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

func (*SimpleOauthCred) Secret

func (self *SimpleOauthCred) Secret() string

func (*SimpleOauthCred) Token

func (self *SimpleOauthCred) Token() string

type SimplePageMapper

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

SimplePageMapper encodes the "landing page" URLs for a particular application as constants.

func NewSimplePageMapper

func NewSimplePageMapper(errUrl string, loginUrl string, logoutUrl string) *SimplePageMapper

NewSimplePageMapper returns an PageMapper that has a simple mapping scheme for where the application URLs just constants.

func (*SimplePageMapper) ErrorPage

func (self *SimplePageMapper) ErrorPage(conn OauthConnector, errorText string) string

Returns the error page and passes the error text message and service name as query parameters to the page.

func (*SimplePageMapper) LoginLandingPage

func (self *SimplePageMapper) LoginLandingPage(conn OauthConnector, state string, code string) string

Returns the login landing page constant with the service name and state passed through as a query parameter. Note, the 'code' probably should not be passed through the client side code!

func (*SimplePageMapper) LogoutLandingPage

func (self *SimplePageMapper) LogoutLandingPage(conn OauthConnector) string

Returns the logout landing page constant. Add's the name of the service to the URL as a query parameter.

type SimplePasswordHandler

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

SimplePasswordHandler is a utility for handling login-logout and authentication checks. It expects to be given a SessionManager that it will work in combination with.

func NewSimplePasswordHandler

func NewSimplePasswordHandler(vsm ValidatingSessionManager, cm CookieMapper) *SimplePasswordHandler

NewSimplePasswordHandler returns a password handler utility object that is associated with the SessionManager provided. Normally the caller will want to bind /me" to MeHandler, /auth to AuthHandler.

func (*SimplePasswordHandler) AuthHandler

func (self *SimplePasswordHandler) AuthHandler(w http.ResponseWriter, r *http.Request)

func (*SimplePasswordHandler) Check

func (self *SimplePasswordHandler) Check(username, pwd string) (Session, error)

Check verifies that the username and password provided are the ones we expect via a calle the ValidatingSessionManager. It returns nil,nil in the case of a failed check on the password provided.

func (*SimplePasswordHandler) MeHandler

func (self *SimplePasswordHandler) MeHandler(w http.ResponseWriter, r *http.Request)

Me returns the currently logged in user to the client.

type SimpleSession

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

SimpleSession is a default implementation of Session suitable for most applications.

func NewSimpleSession

func NewSimpleSession(userData interface{}, sid string) *SimpleSession

NewSimpleSession returns a new simple session with its SessionId initialized. If the sid is "", a new UDID is generated as the session ID, but most applications will want to control this so that sessions are stable across runs.

func (*SimpleSession) SessionId

func (self *SimpleSession) SessionId() string

SessionId returns the sessionId. To make sessions stable across runs, the SimpleSessionManager encodes a unique id and a expiration time into the SessionId and then encrypts that with a key only the session manager knows (so the client side cannot see it).

func (*SimpleSession) UserData

func (self *SimpleSession) UserData() interface{}

UserData returns data you want hanging on the session on the session. Note this does not control/affect the unique id that is typically encoded in the session id.

type SimpleSessionManager

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

SimpleSessionManager is an implementation of the SessionManager that knows about the semantics of getting data from a remote location as part of session creation.

func NewDumbSessionManager

func NewDumbSessionManager() *SimpleSessionManager

NewDumbSessionManager returns a session manager that makes no attempt to conceal the client session id from the client, so this is probably only useful for tests.

func NewSimpleSessionManager

func NewSimpleSessionManager(g Generator) *SimpleSessionManager

NewSimpleSessionManager returns an instance of seven5.SessionManager. This keeps the sessions in memory, not on disk or database but does try to insure that sessions are stable across runs by encrypting the session ids with a key only the session manager knows. The key must be supplied in the environment variable SERVER_SESSION_KEY or this function panics. That key should be a 32 character hex string (see key2hex). If you pass nil as your generator, we are assuming that you will explicitly connect each user session via a call to Assign.

func (*SimpleSessionManager) Assign

func (self *SimpleSessionManager) Assign(uniqueInfo string, userData interface{}, expires time.Time) (Session, error)

Assign is responsible for connecting the unique key for the user to a session. The unique key should not contain colon or comma, email address or primary key from the database are good choices. The userData will be initially assigned to the new session. Note that you can't change the uniqueInfo later without some work, so making it the email address can be trying. The expiration time can be in the past, that is useful for testing. If the expiration time is the time zero value, the expiration time of one day from now will be used.

func (*SimpleSessionManager) Destroy

func (self *SimpleSessionManager) Destroy(id string) error

Destroy is called when a user requests to logout. The value provided should be the session id, not the unique user info.

func (*SimpleSessionManager) Find

func (self *SimpleSessionManager) Find(id string) (*SessionReturn, error)

Find is called by the cookie management layer to see if a particular session is known. In the case where the session is not known, the returned value may be nil for no information or have the UniqueId that was extracted from the sessionid (created on a previous run). If a uniqueId is returned, not a session, it would be wise to create a session immediately since we have confirmed that at some point in the past that sesison existed for this user.

func (*SimpleSessionManager) Generate

func (self *SimpleSessionManager) Generate(uniq string) (interface{}, error)

Generate returns nil,nil if no Generator was provided at the time of this object's creation. If a Generator was provided is it invoked to create the user data from this session.

func (*SimpleSessionManager) Update

func (self *SimpleSessionManager) Update(session Session, i interface{}) (Session, error)

Update is called from the actual response handlers in the web app to inform us that the session's user data needs to change. Note that a different Session will be returned here and this is the new session for that id. The returned session should not be cached but should be looked up with Find each time. Note that you may not change the value of the unique id via this method or everything will go very badly wrong.

type SimpleStaticFilesServer

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

SimpleStaticFileServer is a simple implementation of a file server for static files that is sufficient for most applications. It defaults to serving "/" from "static" (child of the current directory) but this can be changed with the environment variable STATIC_DIR.

func NewStaticFilesServer

func NewStaticFilesServer(mountedAt string, isTestMode bool) *SimpleStaticFilesServer

NewStaticFilesServer returns a new file server and if isTestMode is true and the environment variable GOPATH is set, it will also serve up go source files from the GOPATH. It expects that the prefix "/gopath" will be used for gopath requests. You should supply the place this has been "mounted" in the URL space (usually "/"") in the first parameter.

func (*SimpleStaticFilesServer) ServeHTTP

ServeHTTP retuns a static file or a not found error. This function meets the requirement of net/http#Handler.

type StaticComponent

type StaticComponent interface {
	Page(PBundle, []string, bool) ComponentResult
	//part of the fixed URL space, not including preceding slash
	UrlPrefix() string
}

type StaticFilesServer

type StaticFilesServer interface {
	http.Handler
}

StaticFilesServer is a wrapper around http.Handler that understands about the Gopath for debugging. Note that most applications with complex routing requirements would probably be better off using SimpleComponentMatcher because StaticFilesServer only understands static files, not URL->file mappings.

type ValidatingSessionManager

type ValidatingSessionManager interface {
	SessionManager
	ValidateCredentials(username, password string) (string, interface{}, error)
	SendUserDetails(i interface{}, w http.ResponseWriter) error
	GenerateResetRequest(string) (string, error)
	UseResetRequest(string, string, string) (bool, error)
}

Valdating session manager is one that can also check the validity of a username and password. This can be easily wrapped around a SimpleSessionManager. The ValidateCredentials method should return "" (first return) for a failed login attempt and use the error for something more serious, like the database cannot be reached. If the first returned value from ValidateCredentials is not "" it should be a unique id, both of the first two returned values will be sent to the (nested) session manager's Assign.

type ViewEditCheck

type ViewEditCheck func(pb PBundle, id int64, isView bool) (bool, error)

ViewEditCheck is a function called by SimpleComponentMatcher to determine if a given user (represented by the PBundle from their client) can even see the static file for the given id. Note that this prevents the entire page from loading, independent from what the rest resources would do in the face of such a request. This should return false, err for an error, false, nil to refuse access, and true, nil to allow access. isView is set to true if the url is of the form /foo/123/view or /foo/123/view.html, otherwise isView is false and the url is of the form /foo/123/edit or /foo/123/edit.html.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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