surf

package module
v0.0.0-...-a6b604f Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2019 License: MIT Imports: 32 Imported by: 0

README

Build Status Godoc license

Documentation

Index

Constants

View Source
const CsrfKey = "csrftoken"

CsrfKey is used for lookup of the csrf token, for example inside of the request's header or form

Variables

View Source
var (
	// ErrMiss is returned when performing operation on key is not in use.
	// This is a not found error narrowed to cache cases only.
	ErrMiss = errors.Wrap(ErrNotFound, "cache miss")

	// ErrCacheMalformed is returned whenever an operation cannot be
	// completed because value cannot be serialized or deserialized.
	ErrCacheMalformed = errors.Wrap(ErrMalformed, "cache malformed")
)
View Source
var (
	ErrInternal   = errors.New("internal")
	ErrNotFound   = errors.New("not found")
	ErrMalformed  = errors.New("malformed")
	ErrValidation = errors.New("invalid")
	ErrConstraint = errors.Wrap(ErrValidation, "constraint")
	ErrPermission = errors.Wrap(ErrValidation, "permission denied")
	ErrConflict   = errors.Wrap(ErrValidation, "conflict")
)

Register all base errors that could be used to created more specific instances.

Functions

func CacheMarshal

func CacheMarshal(value interface{}) ([]byte, error)

CacheMarshal returns serialized representation of given value.

Unless given destination implements CacheMarshaler interface, JSON is used to marshal the value.

func CacheUnmarshal

func CacheUnmarshal(raw []byte, dest interface{}) error

CacheUnmarshal deserialize given raw data into given destination.

Unless given destination implements CacheMarshaler interface, JSON is used to unmarshal the value.

func CsrfField

func CsrfField(ctx context.Context) template.HTML

func CsrfToken

func CsrfToken(ctx context.Context) string

CsrfToken returns CSRF protection token attached to given context. Handler must be protected by CsrfMiddleware to have csrf token present in the context.

func LogError

func LogError(ctx context.Context, err error, message string, keyvals ...string)

LogError writes info log message to logger present in given context. Message is discarded if no logger is present in context.

func LogInfo

func LogInfo(ctx context.Context, message string, keyvals ...string)

LogInfo writes info log message to logger present in given context. Message is discarded if no logger is present in context.

func NewHTTPApplication

func NewHTTPApplication(app interface{}, logger Logger, debug bool) http.Handler

func NewRouter

func NewRouter() *router

func PathArg

func PathArg(r *http.Request, index int) string

PathArg return value as matched by path regexp at given index. Indexing of matched values starts with 0. If requested argument is out of index, empty string is returned.

func PathArgInt

func PathArgInt(r *http.Request, index int) int

PathArgInt returns integer value of given path argument. If requested path argument is not valid integer value, 0 is returned. Use correct regular expression to ensure represented value is a valid number.

func PathArgInt64

func PathArgInt64(r *http.Request, index int) int64

PathArgInt64 returns integer value of given path argument. If requested path argument is not valid integer value, 0 is returned. Use correct regular expression to ensure represented value is a valid number.

func RunCacheImplementationTest

func RunCacheImplementationTest(t *testing.T, c CacheService)

Types

type CacheMarshaler

type CacheMarshaler interface {
	MarshalCache() ([]byte, error)
	UnmarshalCache([]byte) error
}

type CacheService

type CacheService interface {
	// Get value stored under given key. Returns ErrMiss if key is not
	// used.
	Get(ctx context.Context, key string, dest interface{}) error

	// Set value under given key. If key is already in use, overwrite it's
	// value with given one and set new expiration time.
	Set(ctx context.Context, key string, value interface{}, exp time.Duration) error

	// SetNx set value under given key only if key is not used. It returns
	// ErrConflict if trying to set value for key that is already in use.
	SetNx(ctx context.Context, key string, value interface{}, exp time.Duration) error

	// Del deletes value under given key. It returns ErrCacheMiss if given
	// key is not used.
	Del(ctx context.Context, key string) error
}

func NewFilesystemCache

func NewFilesystemCache(rootDir string) CacheService

func PrefixCache

func PrefixCache(cache CacheService, prefix string) CacheService

func StampedeProtect

func StampedeProtect(cache CacheService) CacheService

func TraceCache

func TraceCache(cache CacheService, prefix string) CacheService

type EnvConf

type EnvConf struct {
	OnErr func(error)
	// contains filtered or unexported fields
}

func NewEnvConf

func NewEnvConf() *EnvConf

NewEnvConf returns configuration instance that use environment variable for configuration.

func (*EnvConf) Bool

func (c *EnvConf) Bool(name string, fallback bool, description string) bool

func (*EnvConf) Duration

func (c *EnvConf) Duration(name string, fallback time.Duration, description string) time.Duration

func (*EnvConf) Int

func (c *EnvConf) Int(name string, fallback int, description string) int

func (*EnvConf) Secret

func (c *EnvConf) Secret(name, fallback, description string) string

func (*EnvConf) Str

func (c *EnvConf) Str(name, fallback, description string) string

func (*EnvConf) WriteHelp

func (c *EnvConf) WriteHelp(w io.Writer)

WriteHelp write information about used environment variables, their value in current environment and description if provided.

type HTMLRenderer

type HTMLRenderer interface {
	Response(ctx context.Context, statusCode int, templateName string, templateContext interface{}) Response
}

func NewHTMLRenderer

func NewHTMLRenderer(templatesGlob string, debug bool, funcs template.FuncMap) HTMLRenderer

NewHTMLRenderer returns HTMLRenderer instance. Default surf template set is extended by templates found in provided path and by passed function mapping.

When running in debug mode, templates are always compiled before rendering. In non debug mode, templates are compiled once and reused to achieve better performance. When in debug mode, all template errors are rendered with explanation and additional information, instead of generic error page.

type Handler

type Handler interface {
	HandleHTTPRequest(http.ResponseWriter, *http.Request) Response
}

func AsHandler

func AsHandler(h interface{}) Handler

AsHandler takes various handler notations and converts them to surf's Handler. If given handler does not implement any known interface, nil and false is returned

func WithMiddlewares

func WithMiddlewares(handler interface{}, middlewares []Middleware) Handler

WithMiddlewares attach given collection of middlewares. First one is called last.

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request) Response

func (HandlerFunc) HandleHTTPRequest

func (fn HandlerFunc) HandleHTTPRequest(w http.ResponseWriter, r *http.Request) Response

type LocalMemCache

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

func NewLocalMemCache

func NewLocalMemCache() *LocalMemCache

NewLocalMemCache returns local memory cache intance. This is strictly for testing and must not be used for end application.

func (*LocalMemCache) Del

func (c *LocalMemCache) Del(ctx context.Context, key string) error

func (*LocalMemCache) Flush

func (c *LocalMemCache) Flush()

func (*LocalMemCache) Get

func (c *LocalMemCache) Get(ctx context.Context, key string, dest interface{}) error

func (*LocalMemCache) ServeHTTP

func (c *LocalMemCache) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*LocalMemCache) Set

func (c *LocalMemCache) Set(ctx context.Context, key string, value interface{}, exp time.Duration) error

func (*LocalMemCache) SetNx

func (c *LocalMemCache) SetNx(ctx context.Context, key string, value interface{}, exp time.Duration) error

type Logger

type Logger interface {
	Info(context.Context, string, ...string)
	Error(context.Context, error, string, ...string)
}

func Discard

func Discard() Logger

Discard returns Logger instance that drops all entries. It's the /dev/null of loggers

func NewLogger

func NewLogger(out io.Writer, keyvals ...string) Logger

type Middleware

type Middleware func(handler interface{}) Handler

Middleware is a function that takes handler in one of recognized by surf notations and returns new handler, wrapping original one with additional functionality.

func CsrfMiddleware

func CsrfMiddleware(
	cache UnboundCacheService,
	tmpl HTMLRenderer) Middleware

func DebugToolbarMiddleware

func DebugToolbarMiddleware(rootPath string) Middleware

func LoggingMiddleware

func LoggingMiddleware(logger Logger) Middleware

func PanicMiddleware

func PanicMiddleware(logger Logger) Middleware

func TracingMiddleware

func TracingMiddleware(frequency time.Duration) Middleware

TracingMiddleware provides trace in request's context with given frequency.

type Paginator

type Paginator struct {
	Total    int64
	PageSize int
	Page     int
}

func (*Paginator) CurrentPage

func (p *Paginator) CurrentPage() int

func (*Paginator) HasNextPage

func (p *Paginator) HasNextPage() bool

func (*Paginator) HasPrevPage

func (p *Paginator) HasPrevPage() bool

func (*Paginator) NextPage

func (p *Paginator) NextPage() int

func (*Paginator) PageCount

func (p *Paginator) PageCount() int

func (*Paginator) Pages

func (p *Paginator) Pages() []PaginatorPage

func (*Paginator) PrevPage

func (p *Paginator) PrevPage() int

type PaginatorPage

type PaginatorPage struct {
	Number  int
	Active  bool
	IsFirst bool
	IsLast  bool
}

type Response

type Response interface {
	http.Handler
}

func JSONErr

func JSONErr(code int, errText string) Response

JSONErr write single error as JSON encoded response.

func JSONErrs

func JSONErrs(code int, errs []string) Response

JSONErrs write multiple errors as JSON encoded response.

func JSONResp

func JSONResp(code int, content interface{}) Response

JSONResp write content as JSON encoded response.

func Redirect

func Redirect(url string, responseCode int) Response

Redirect returns Response instance that redirects client to another endpoint.

func StdJSONResp

func StdJSONResp(code int) Response

StdJSONResp write JSON encoded, standard HTTP response text for given status code. Depending on status, either error or successful response format is used.

func StdResponse

func StdResponse(ctx context.Context, r HTMLRenderer, responseCode int) Response

StdResponse returns Response instance with generic HTML page for given return code.

type Route

type Route interface {
	Use(middlewares ...Middleware) Route

	Add(method string, handler interface{}) Route

	Get(handler interface{}) Route
	Post(handler interface{}) Route
	Put(handler interface{}) Route
	Delete(handler interface{}) Route
	Head(handler interface{}) Route
	Options(handler interface{}) Route
	Trace(handler interface{}) Route
	Patch(handler interface{}) Route
}

type TraceSpan

type TraceSpan interface {
	// Begin creates and remove new measurement span. Current span is set
	// as parent of newly created and returned one.
	//
	// It is users responsibility to finish span.
	Begin(description string, keyvalues ...string) TraceSpan

	// Finish close given span and finalize measurement.
	Finish(keyvalues ...string)
}

func CurrentTrace

func CurrentTrace(ctx context.Context) TraceSpan

CurrentTrace returns TraceSpan that is attached to given context. This function always returns valid TraceSpan implementation and it is safe to use the result. When no trace is attached to context, implementation that is discarding results is provided. CurrentTrace alwasys returns first TraceSpan that covers the whole measurement period.

type URLPath

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

func Path

func Path(path string) *URLPath

func (*URLPath) LastChunk

func (p *URLPath) LastChunk() string

type UnboundCacheService

type UnboundCacheService interface {
	Bind(http.ResponseWriter, *http.Request) CacheService
}

func NewCookieCache

func NewCookieCache(prefix string, secret []byte) (UnboundCacheService, error)

func NewUnboundCache

func NewUnboundCache(cache CacheService, key string) UnboundCacheService

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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