gowork

package module
v0.0.0-...-2a3c3ea Latest Latest
Warning

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

Go to latest
Published: May 18, 2016 License: GPL-2.0 Imports: 25 Imported by: 0

README

gowork

Simple GO/HTTP/Cassandra web application framework.

Documentation

Index

Constants

View Source
const (
	STALE_ENTITY_MSG     = "Stale Entity. It has been updated in another session! Please reload and try again."
	CANNOT_BE_ZERO_VALUE = "value cannot be 'zero' value"
)
View Source
const (
	ACCESS EventCode = "ACCESS"
	CREATE EventCode = "CREATE"
	DELETE EventCode = "DELETE"
	DENIED EventCode = "DENIED"
	ERROR  EventCode = "ERROR"
	READ   EventCode = "READ"
	UPDATE EventCode = "UPDATE"

	LOGIN      Permission = "LOGIN"
	SUPER_USER Permission = "SUPER_USER" //Has all permissions except LOGIN
)
View Source
const (
	DEFAULT_CONSISTENCY = gocql.LocalQuorum
)

Variables

View Source
var Letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
View Source
var Zero = MonetaryAmount{Dec: decZero}

Functions

func Cache

func Cache(ctx Context, name, key string, function func() (interface{}, error)) (interface{}, error)

func CeilingDay

func CeilingDay(t time.Time) time.Time

func CeilingMonth

func CeilingMonth(t time.Time) time.Time

func CeilingWeek

func CeilingWeek(t time.Time) time.Time

func CeilingYear

func CeilingYear(t time.Time) time.Time

func ChopSlice

func ChopSlice(slice interface{}, field string) (interface{}, error)

ChopSlice returns a map of the input slice grouped by the specified field name.

func ChopSortedSlice

func ChopSortedSlice(slice interface{}, field string) (interface{}, error)

ChopSortedSlice is similar to ChopSlice except rather than returning new slices for the map values it just re-slices the input slice, as a result the input slice must be sorted. If the input slice is not sorted the results are undefined.

func ClearOffset

func ClearOffset()

func CurrentFunctionName

func CurrentFunctionName(stack int) string

func CurrentTime

func CurrentTime() time.Time

CurrentTime should be used throughout the entire system when the current time is needed. This allows the testing infrastructure to use offsets.

func Date

func Date(r *http.Request) time.Time

func DayBefore

func DayBefore(t time.Time) time.Time

func DaysBefore

func DaysBefore(t time.Time, days int) time.Time

func DumpSlice

func DumpSlice(slice interface{})

DumpSlice is used to dump the contents of a slice out to std out and is useful in testing.

func FloorDay

func FloorDay(t time.Time) time.Time

func FloorMonth

func FloorMonth(t time.Time) time.Time

func FloorWeek

func FloorWeek(t time.Time) time.Time

func FloorYear

func FloorYear(t time.Time) time.Time

func FormatJSON

func FormatJSON(src string) string

FormatJSON is a quick utility method to format JSON. Primarily used in logging/testing as it doesn't return an error on failure.

func FromJulianDate

func FromJulianDate(str string) time.Time

func FunctionName

func FunctionName(i interface{}) string

func IsNotZeroValue

func IsNotZeroValue(v interface{}, param string) error

IsNotZeroValueDeep is a function used by the validator.V2 GO lib. It should only be used on Structs for performance reasons. Builtins will perform much better using the 'nonzero' validator provided by the lib.

func JSONResponse

func JSONResponse(w http.ResponseWriter, data interface{}, err interface{})

func Limit

func Limit(r *http.Request) (limit int)

func MarshalDate

func MarshalDate(t time.Time) string

func NewReadCloserFromString

func NewReadCloserFromString(string string) io.ReadCloser

func RandomString

func RandomString(num int) string

func RandomStringSelection

func RandomStringSelection(num int, values []rune) string

func SetOffset

func SetOffset(val time.Duration)

SetOffset is only used for testing. It is used when you want to move the state of the application ahead of forward by the provided duration in order to test time sensitive code. Jobs, etc...

func SetOffsetTime

func SetOffsetTime(date time.Time)

SetOffsetTime is only used for testing. It is used when you want to move the state of the application ahead of forward by the provided duration in order to test time sensitive code. Jobs, etc...

func SliceContains

func SliceContains(slice interface{}, v interface{}) bool

func StringFromReadCloser

func StringFromReadCloser(r io.ReadCloser) string

func StringMapToSlice

func StringMapToSlice(m map[string]interface{}) interface{}

func StringPrefixMatch

func StringPrefixMatch(full string, prefixes []string) bool

func StringValue

func StringValue(i interface{}, fieldName string) string

func StructName

func StructName(i interface{}) string

func SubtractMonth

func SubtractMonth(t time.Time) time.Time

SubtractMonth subtracts one month from the provided value like AddDate, but unlike AddDate it will not normalize dates. i.e. With AddDate: "December 31st".AddDate(0, -1, 0) results in December 1st because there is no November 31st. With SubtractMonth "December 31st" becomes November 30.

func ToJulianDate

func ToJulianDate(t time.Time) (date string)

func TrimAllSpace

func TrimAllSpace(str []string)

func UnMarshalDate

func UnMarshalDate(datestr string) (time.Time, error)

func WriteErrorToJSON

func WriteErrorToJSON(w http.ResponseWriter, code int, err interface{})

func WriteJSON

func WriteJSON(w http.ResponseWriter, data interface{})

func WriteMessageToJSON

func WriteMessageToJSON(w http.ResponseWriter, message string)

Types

type Cassandra

type Cassandra struct {
	Session     *gocql.Session
	Debug       bool
	Unmarshaler unmarshaler
	Partition   string //TODO:Stan it is unlikely that all tables will have the same partition interval (i.e. date, hour, etc..). Look at a way to expand/replace this.
}

func (*Cassandra) BuildInsertStatement

func (c *Cassandra) BuildInsertStatement(table string, entity interface{}, overrides map[string]interface{}) (string, []interface{})

func (*Cassandra) BuildUpdateStatement

func (c *Cassandra) BuildUpdateStatement(table string, entity interface{}, overrides map[string]interface{}) (string, []interface{})

BuildUpdateStatement builds a Cassandra Update statement based on the provided entity and overrides. Right now it only works for entities with a single id field named id or tagged with "datastore=id".

func (*Cassandra) GetAll

func (c *Cassandra) GetAll(table string, limit int, partition time.Time, entity interface{}, consistency gocql.Consistency) (entities interface{}, err error)

func (*Cassandra) GetById

func (c *Cassandra) GetById(table string, id string, partition time.Time, entity interface{}, consistency gocql.Consistency) (err error)

GetById is a utility function used to simplify loading an entity from the datastore by Id. Partition Time is optional and is only used by tables that have a partition string partition key.

func (*Cassandra) Insert

func (c *Cassandra) Insert(table string, entity interface{}, overrides map[string]interface{}, consistency gocql.Consistency) error

Builds a CQL INSERT INTO statement with the provided information and executes it. Overrides is a map keyed on the datastore tag that allows different values to be specified than the value provided in entity.

func (*Cassandra) Update

func (c *Cassandra) Update(table string, entity interface{}, overrides map[string]interface{}, consistency gocql.Consistency) error

TODO: Modify this to work with CAS tables. Builds a CQL UPDATE statement with the provided information and executes it. Overrides is a map keyed on the datastore tag that allows different values to be specified than the value provided in entity.

type Config

type Config struct {
	Id          string    `json:"id" datastore:"id"`
	Created     time.Time `json:"created,omitempty" validate:"nonzero" datastore:"cr"`
	Description string    `json:"desc,omitempty" validate:"nonzero" datastore:"descr"`
	Value       string    `json:"value,omitempty" validate:"nonzero"`
	Version     int       `json:"v,omitempty" validate:"min=0" datastore:"v"`
}

type Context

type Context interface {
	Get(key interface{}) interface{}
	Put(key interface{}, value interface{})

	//Utility method to reduce some repeating code
	GetString(key interface{}) string
}

Context wraps the Gorilla context and is used to store things unique to each HTTP Request.

func GetContext

func GetContext(r *http.Request) (ctx Context)

type ContextHandler

type ContextHandler struct {
	NewRequestContext newRequestContext
}

ContextHandler is a simple http.Handler that attaches the configured Impl Context to the Gorilla Context. It effectively hides the Gorilla Context from the rest of the application.

func (*ContextHandler) New

func (s *ContextHandler) New(handler http.Handler) http.Handler

type ContextKey

type ContextKey string
const (
	ReqCtx ContextKey = "REQ_CTX"
)

type CookieStore

type CookieStore struct {
	Codecs          []securecookie.Codec
	Options         *sessions.Options // default configuration
	SessionProvider SessionProvider
}

func (*CookieStore) ConvertToInterfaceMap

func (s *CookieStore) ConvertToInterfaceMap(in map[string]string) (out map[interface{}]interface{})

func (*CookieStore) ConvertToStringMap

func (s *CookieStore) ConvertToStringMap(in map[interface{}]interface{}) (out map[string]string)

func (*CookieStore) Get

func (s *CookieStore) Get(r *http.Request, name string) (*sessions.Session, error)

Get returns a session for the given name after adding it to the registry.

See CookieStore.Get().

func (*CookieStore) MaxLength

func (s *CookieStore) MaxLength(l int)

MaxLength restricts the maximum length of new sessions to l. If l is 0 there is no limit to the size of a session, use with caution. The default for a new FilesystemStore is 4096.

func (*CookieStore) New

func (s *CookieStore) New(r *http.Request, name string) (*sessions.Session, error)

New returns a session for the given name without adding it to the registry.

See CookieStore.New().

func (*CookieStore) Save

func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error

Save adds a single session to the response.

type DebugHandler

type DebugHandler struct {
	Debug bool
	Name  string
}

func (*DebugHandler) New

func (s *DebugHandler) New(handler http.Handler) http.Handler

type Error

type Error struct {
	Field   string `json:"field,omitempty"`
	Message string `json:"msg"`
	Index   int    `json:"index,omitempty"`
}

type ErrorResponse

type ErrorResponse struct {
	Errors []Error `json:"errors"`
	Count  int     `json:"count"`
}

func (*ErrorResponse) Add

func (er *ErrorResponse) Add(error Error)

type EventCode

type EventCode string

type IndexedError

type IndexedError struct {
	Err   error
	Index int
}

func (IndexedError) Error

func (e IndexedError) Error() string

type MemTable

type MemTable struct {
	Table map[string]interface{}

	Debug bool
	// contains filtered or unexported fields
}

func NewMemTable

func NewMemTable() *MemTable

func (*MemTable) All

func (mt *MemTable) All() interface{}

func (*MemTable) Create

func (mt *MemTable) Create(id string, o interface{}) error

Create makes a new table entry with the provided id. An error is never returned from this function and is intended for use in overriding functions.

func (MemTable) Dump

func (mt MemTable) Dump()

func (*MemTable) Get

func (mt *MemTable) Get(id string) (interface{}, error)

func (*MemTable) GetAll

func (mt *MemTable) GetAll(date time.Time, limit int, entity interface{}) (interface{}, error)

TODO:Stan date is a project specific item. Should really move it out of here and into the various other projects.

func (*MemTable) Update

func (mt *MemTable) Update(id string, o interface{}) error

type Message

type Message struct {
	Message string `json:"msg"`
}

type MonetaryAmount

type MonetaryAmount struct {
	*inf.Dec
	Currency currencies.Currency
}

Minimal hiding of the underlying Decimal implementation so API changes or a when better implementation comes along it won't cause huge app changes.

func MonetaryAmountFromString

func MonetaryAmountFromString(value string, cur string) (amount MonetaryAmount, err error)

func MonetaryAmountFromStringPanic

func MonetaryAmountFromStringPanic(value string, cur string) MonetaryAmount

MonetaryAmountFromStringPanic is just like MonetaryAmountFromString only it will panic if the string is invalid. Useful for things like unit tests where the amount is hardcoded in the test.

func NewMonetaryAmount

func NewMonetaryAmount(currency currencies.Currency) MonetaryAmount

func (MonetaryAmount) Abs

func (MonetaryAmount) Add

Add will add the provided MonetaryAmount to the current MonetaryAmount and return a new MonetaryAmount with the summed value. It will panic if the currencies differ.

func (MonetaryAmount) AssumeScale

func (m MonetaryAmount) AssumeScale(scale int) int64

func (MonetaryAmount) Cmp

func (m MonetaryAmount) Cmp(ma MonetaryAmount) int

Cmp compares the provided MonetaryAmount to the current MonetaryAmount and return -1, 0, 1 based on the underlying inf.Dec.Cmp function. Ignores Currency.

func (MonetaryAmount) IsZero

func (m MonetaryAmount) IsZero() bool

func (MonetaryAmount) Multiply

func (m MonetaryAmount) Multiply(i *inf.Dec) MonetaryAmount

func (MonetaryAmount) Neg

func (MonetaryAmount) Round

func (m MonetaryAmount) Round(scale int) MonetaryAmount

func (MonetaryAmount) String

func (m MonetaryAmount) String() string

func (MonetaryAmount) StringWithCurrency

func (m MonetaryAmount) StringWithCurrency() string

func (*MonetaryAmount) UnmarshalText

func (m *MonetaryAmount) UnmarshalText(data []byte) error

UnmarshalText mutates the current MonetaryAmount instance with the provided byte array.

type NotFoundError

type NotFoundError string

func NewNotFoundError

func NewNotFoundError() NotFoundError

func NewStaleEntityError

func NewStaleEntityError() NotFoundError

func (NotFoundError) Error

func (s NotFoundError) Error() string

type Permission

type Permission string

type Permissions

type Permissions []Permission

func (*Permissions) HasPermission

func (u *Permissions) HasPermission(perm Permission) bool

type RequestContext

type RequestContext struct {
	SimpleRequestContext
}

RequestContext is just a wrapper on SimpleRequestContext for the time being.

type Session

type Session struct {
	Id         string            `json:"id"`
	Created    time.Time         `json:"created" validate:"nonzero" datastore:"cr"`
	LastAccess time.Time         `json:"access" validate:"nonzero" datastore:"access"`
	Values     map[string]string `json:"values" validate:"nonzero"` //TODO:Stan investigate changing value to interface or []byte
	UserId     string            `json:"userid" validate:"nonzero"`
	Version    int               `json:"v" validate:"min=0" datastore:"v"`
}

type SessionProvider

type SessionProvider interface {
	GetSession(ctx Context, id string) (*Session, error)
	CreateSession(ctx Context, session *Session) error
	UpdateSession(ctx Context, session *Session) (err error)
}

type SimpleContext

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

SimpleContext is the simplest implementation of a Context used by the application.

func NewSimpleContext

func NewSimpleContext() *SimpleContext

func (*SimpleContext) Get

func (ac *SimpleContext) Get(key interface{}) interface{}

func (*SimpleContext) GetString

func (ac *SimpleContext) GetString(key interface{}) (str string)

func (*SimpleContext) Put

func (ac *SimpleContext) Put(key interface{}, value interface{})

type SimpleRequestContext

type SimpleRequestContext struct {
	Request *http.Request
	SimpleContext
}

func NewSimpleRequestContext

func NewSimpleRequestContext(r *http.Request) *SimpleRequestContext

type StaleEntityError

type StaleEntityError string

func (StaleEntityError) Error

func (s StaleEntityError) Error() string

type StaticAssetHandler

type StaticAssetHandler struct {
	AssetUrlPrefix string
	AssetUrls      []string
	AssetFilePath  string
}

func (*StaticAssetHandler) IsStaticAsset

func (s *StaticAssetHandler) IsStaticAsset(url string) bool

func (*StaticAssetHandler) New

func (s *StaticAssetHandler) New(handler http.Handler) http.Handler

type Transport

type Transport interface {
	Connect(args ...interface{}) error
	Upload(path string, content *bytes.Buffer) error
	Download(path string, content *bytes.Buffer) error
	List(path string) ([]os.FileInfo, error)
	Raw(args ...interface{}) ([]interface{}, error)
	Close() error
}

type User

type User interface {
	HasPermission(p Permission) bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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