gocaveman

package module
v0.0.0-...-307aa89 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2017 License: LGPL-3.0 Imports: 32 Imported by: 0

README

gocaveman

Website primitives that don't suck.

EXPERIMENTAL FOR NOW, WILL UPDATE WITH COOL STUFF SOON.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrExceededLimit = fmt.Errorf("exceeded limit")
View Source
var ErrNotFound = errors.New("not found")
View Source
var ErrNotJSONContent = errors.New("cannot parse, not json content")
View Source
var VALID_TOKEN_REGEXP = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)

Functions

func AtoiAnyDef

func AtoiAnyDef(s interface{}, vdef int) int

func AtoiDef

func AtoiDef(s string, vdef int) int

func BuildHandlerChain

func BuildHandlerChain(hl HandlerList) http.Handler

BuildHandlerChain takes a HandlerList (slice of http.Handler instances) and finds any that implement ChainedHandler and calls SetNextHandler() with the appropriate input to form a chain. The return value is a handler that calls the other handlers in the correct sequence, taking into account the intended behavior of SetNextHandler.

func CheckValidToken

func CheckValidToken(t string) error

func CtxIsHTTPS

func CtxIsHTTPS(ctx context.Context) bool

func CtxWithCombinedPath

func CtxWithCombinedPath(ctx context.Context, pathType string, resourcePath string) context.Context

func CtxWithHTTPS

func CtxWithHTTPS(ctx context.Context) context.Context

func CtxWithHTTPSHandler

func CtxWithHTTPSHandler(next http.Handler) http.Handler

func CtxWithPageMeta

func CtxWithPageMeta(ctx context.Context, pageMeta *PageMeta) context.Context

func DefaultPathExpand

func DefaultPathExpand(p string) []string

func DefaultRedirects

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

func GuessMIMEType

func GuessMIMEType(p string) string

GuessMIMEType is a thin wrapper around mime.TypeByExtension(), but with some common sense defaults that are sometimes different/wrong on different platforms for no good reason.

func HTTPError

func HTTPError(w http.ResponseWriter, r *http.Request, err error, publicMessage string, code int) error

Reads and reports an http error - does not expose anything to the outside world except a unique ID, which can be matched up with the appropriate log statement which has the details.

func IsPEMCertData

func IsPEMCertData(v []byte) bool

IsPEMCertData returns true if v contains "-----BEGIN", "CERTIFICATE-----" and at least one newline.

func IsPEMKeyData

func IsPEMKeyData(v []byte) bool

IsPEMKeyData returns true if v contains "-----BEGIN", "PRIVATE KEY-----" and at least one newline.

func JSONMarshalResponse

func JSONMarshalResponse(w http.ResponseWriter, status int, v interface{}) error

func JSONUnmarshalRequest

func JSONUnmarshalRequest(r *http.Request, v interface{}) error

func LoadKeyPairAuto

func LoadKeyPairAuto(cert, key string) (tls.Certificate, error)

LoadKeyPairAuto looks at the parameters and loads the certificate(s) and key either from the path pointed to on disk or directly as PEM data. IsPEMKeyData and IsPEMCertData to detect key and cert data in PEM format. This is a simple wrapper around tls.X509KeyPair.

func LogToSyslog

func LogToSyslog(prgName string) error

func NewDefaultDBBlogSite

func NewDefaultDBBlogSite()

pages are in db but the rest is in fs? - figure out the variations here...

func NewDefaultDBOnlySite

func NewDefaultDBOnlySite()

func NewDefaultFSOnlySite

func NewDefaultFSOnlySite()

func NewDefaultRedirects

func NewDefaultRedirects() http.Handler

NewDefaultRedirects returns a helper handler to normalize URLs by 301 redirecting common variations that would otherwise create duplicate URLs.

func NewHTTPFuncFS

func NewHTTPFuncFS(f func(name string) (http.File, error)) http.FileSystem

func ParseMetaAndText

func ParseMetaAndText(b []byte, meta interface{}) (tmpltext []byte, e error)

func ReadJSON

func ReadJSON(r *http.Request, va interface{}) error

func WalkRenderAndIndex

func WalkRenderAndIndex(bodyFs http.FileSystem, fileExts []string, renderer Renderer, pageIndex *PageIndex) error

WalkRenderAndIndex is a helper to glue together the Renderer and PageIndex, since these two are intentionally kept unaware of each other. This walks the file system and calls the Renderer for each file found, adding the approrpiate PageMeta to the PageIndex. FIXME: fileExts moves to some kinda of Options struct and we also need a way to regexp exclude, as well as specify removal of file extension.

func WriteJSON

func WriteJSON(w http.ResponseWriter, va interface{}, code int)

FIXME de-duplicate between this and JSONMarshalResponse

Types

type AssetDirFunc

type AssetDirFunc func(path string) ([]string, error)

type AssetFunc

type AssetFunc func(path string) ([]byte, error)

type AssetInfoFunc

type AssetInfoFunc func(path string) (os.FileInfo, error)

type BodyTemplater

type BodyTemplater interface {
	BodyTemplate(io.Reader) (*PageMeta, string, error)
}

BodyTemplater reads the body of a page and returns a string with the appropriate Go template. Pages that are already Go templates can be returned as-is but this interface allows us to implement markdown or other languages by converting them to Go templates.

type ChainedHandler

type ChainedHandler interface {
	http.Handler
	SetNextHandler(next http.Handler) (self ChainedHandler)
}

type CtxMapHandler

type CtxMapHandler struct {
	CtxMap      map[string]interface{}
	NextHandler http.Handler
}

CtxMapHandler sets static items in the context during each request.

func NewCtxMapHandler

func NewCtxMapHandler(ctxMap map[string]interface{}) *CtxMapHandler

func (*CtxMapHandler) ServeHTTP

func (h *CtxMapHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*CtxMapHandler) SetNextHandler

func (h *CtxMapHandler) SetNextHandler(next http.Handler) ChainedHandler

type DebugResponseWriterCloser

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

DebugResponseWriterCloser

func DebugCtxWrap

FIXME: figure out if we're going to keep the debug/dumping stuff in here or not - might be useful but needs think-through DebugCtxWrap is like GzipCtxWrap but instead of gzipping it implements debug logging that dumps full responses to the log. Use DumpRequest to dump the request in the same format.

func (*DebugResponseWriterCloser) Close

func (w *DebugResponseWriterCloser) Close() error

Close dumps the response using log.Printf

func (*DebugResponseWriterCloser) DumpRequest

func (w *DebugResponseWriterCloser) DumpRequest(r *http.Request)

DumpRequest is a helper to dump a request in the same format that Close() dumps the response

func (*DebugResponseWriterCloser) Flush

func (w *DebugResponseWriterCloser) Flush()

func (*DebugResponseWriterCloser) Write

func (w *DebugResponseWriterCloser) Write(p []byte) (int, error)

func (*DebugResponseWriterCloser) WriteHeader

func (w *DebugResponseWriterCloser) WriteHeader(c int)

type DefaultCacheHeadersHandler

type DefaultCacheHeadersHandler struct{}

TODO: we should add a good HTTPError here, it's pretty darned useful

func (*DefaultCacheHeadersHandler) ServeHTTP

type DummyResponseWriterCloser

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

DummyResponseWriterCloser implements only the context cancellation and otherwise does nothing.

func (*DummyResponseWriterCloser) Close

func (w *DummyResponseWriterCloser) Close() error

func (*DummyResponseWriterCloser) Flush

func (w *DummyResponseWriterCloser) Flush()

func (*DummyResponseWriterCloser) Write

func (w *DummyResponseWriterCloser) Write(p []byte) (int, error)

func (*DummyResponseWriterCloser) WriteHeader

func (w *DummyResponseWriterCloser) WriteHeader(c int)

type FileCombiner

type FileCombiner struct {
	PageIndex   *PageIndex
	NextHandler http.Handler
}

func (*FileCombiner) ServeHTTP

func (fc *FileCombiner) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*FileCombiner) SetNextHandler

func (fc *FileCombiner) SetNextHandler(next http.Handler) ChainedHandler

type GoBodyTemplater

type GoBodyTemplater struct{}

func (*GoBodyTemplater) BodyTemplate

func (t *GoBodyTemplater) BodyTemplate(r io.Reader) (*PageMeta, string, error)

type GzipHandler

type GzipHandler struct {
	NextHandler http.Handler
}

func NewGzipHandler

func NewGzipHandler() *GzipHandler

func (*GzipHandler) ServeHTTP

func (h *GzipHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*GzipHandler) SetNextHandler

func (h *GzipHandler) SetNextHandler(next http.Handler) ChainedHandler

type GzipResponseWriterCloser

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

GzipResponseWriterCloser implements gzip writing and context cancellation.

func (*GzipResponseWriterCloser) Close

func (w *GzipResponseWriterCloser) Close() error

func (*GzipResponseWriterCloser) Flush

func (w *GzipResponseWriterCloser) Flush()

func (*GzipResponseWriterCloser) Header

func (w *GzipResponseWriterCloser) Header() http.Header

func (*GzipResponseWriterCloser) Write

func (w *GzipResponseWriterCloser) Write(p []byte) (int, error)

func (*GzipResponseWriterCloser) WriteHeader

func (w *GzipResponseWriterCloser) WriteHeader(c int)

type HTTPBindataFile

type HTTPBindataFile struct {
	*bytes.Reader
	// contains filtered or unexported fields
}

func (*HTTPBindataFile) Close

func (f *HTTPBindataFile) Close() error

func (*HTTPBindataFile) Name

func (f *HTTPBindataFile) Name() string

func (*HTTPBindataFile) Readdir

func (f *HTTPBindataFile) Readdir(int) ([]os.FileInfo, error)

func (*HTTPBindataFile) Stat

func (f *HTTPBindataFile) Stat() (os.FileInfo, error)

type HTTPBindataFs

type HTTPBindataFs struct {
	AssetFunc
	AssetDirFunc
	AssetInfoFunc
	Prepend string // require this in front of a name request in order to satisfy it (i.e. make it appear like all files are under this dir)
}

func (*HTTPBindataFs) Open

func (fs *HTTPBindataFs) Open(name string) (http.File, error)

type HTTPBytesFile

type HTTPBytesFile struct {
	*bytes.Reader
	// contains filtered or unexported fields
}

func NewHTTPBytesFile

func NewHTTPBytesFile(name string, modTime time.Time, data []byte) *HTTPBytesFile

func (*HTTPBytesFile) Close

func (f *HTTPBytesFile) Close() error

func (*HTTPBytesFile) Readdir

func (f *HTTPBytesFile) Readdir(count int) ([]os.FileInfo, error)

func (*HTTPBytesFile) Stat

func (f *HTTPBytesFile) Stat() (os.FileInfo, error)

type HTTPFileInfo

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

HTTPFileInfo implements os.FileInfo

func NewHTTPFileInfo

func NewHTTPFileInfo(name string, size int64, mode os.FileMode, modTime time.Time, sys interface{}) *HTTPFileInfo

func (*HTTPFileInfo) IsDir

func (i *HTTPFileInfo) IsDir() bool

IsDir is an abbreviation for Mode().IsDir()

func (*HTTPFileInfo) ModTime

func (i *HTTPFileInfo) ModTime() time.Time

ModTime returns the modification time

func (*HTTPFileInfo) Mode

func (i *HTTPFileInfo) Mode() os.FileMode

Mode returns file mode bits

func (*HTTPFileInfo) Name

func (i *HTTPFileInfo) Name() string

Name returns the base name of the file

func (*HTTPFileInfo) Size

func (i *HTTPFileInfo) Size() int64

Size returns the length in bytes

func (*HTTPFileInfo) Sys

func (i *HTTPFileInfo) Sys() interface{}

Sys is underlying data source (can return nil)

type HTTPFuncFS

type HTTPFuncFS func(name string) (http.File, error)

func (HTTPFuncFS) Open

func (f HTTPFuncFS) Open(name string) (http.File, error)

type HTTPStackedFileSystem

type HTTPStackedFileSystem struct {
	Stack []http.FileSystem
}

HTTPStackedFileSystem implements http.FileSystem by falling back through multiple layers to find where a file exists and using the first match. FileSystems are checked in the order provided, i.e. index 0 takes precedence over all others, etc.

func NewHTTPStackedFileSystem

func NewHTTPStackedFileSystem(subfss ...http.FileSystem) *HTTPStackedFileSystem

func (*HTTPStackedFileSystem) Open

func (fs *HTTPStackedFileSystem) Open(name string) (ret http.File, err error)

type HandlerList

type HandlerList []http.Handler

func (HandlerList) ServeHTTP

func (hl HandlerList) ServeHTTP(w http.ResponseWriter, r *http.Request)

type MarkdownBodyTemplater

type MarkdownBodyTemplater struct {
	TemplatePrefix string
	TemplateSuffix string
}

func NewMarkdownBodyTemplater

func NewMarkdownBodyTemplater() *MarkdownBodyTemplater

func (*MarkdownBodyTemplater) BodyTemplate

func (t *MarkdownBodyTemplater) BodyTemplate(r io.Reader) (*PageMeta, string, error)

type PageIndex

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

type PageMeta

type PageMeta struct {
	HTMLTitle       string `yaml:"html_title"`       // <title> tag
	MetaDescription string `yaml:"meta_description"` // meta description tag
	ShortTitle      string `yaml:"short_title"`      // optional shorter version of title for listing pages, etc.

	Locale string

	Data map[string]interface{}
}

type PathParser

type PathParser struct {
	Args []string // arguments matched, 0 indexed
}

PathParser is a simple helper to match paths and extract parts from them.

func (*PathParser) ArgInt

func (pp *PathParser) ArgInt(n int) (ret int)

func (*PathParser) ArgIntDef

func (pp *PathParser) ArgIntDef(n int, defaultVal int) (ret int)

func (*PathParser) ArgString

func (pp *PathParser) ArgString(n int) (ret string)

func (*PathParser) ArgStringDef

func (pp *PathParser) ArgStringDef(n int, defaultVal string) (ret string)

func (*PathParser) ArgUUIDB64

func (pp *PathParser) ArgUUIDB64(n int) gouuidv6.UUIDB64

func (*PathParser) Match

func (pp *PathParser) Match(path string, pattern string) bool

Match looks at a path against a pattern if it matches returns true and replaces the Args with the matches. Placeholders can be "%S" (any non-empty string not containing a slash) or "%d" (any decimal number).

type RenderHandler

type RenderHandler interface {
	ServeHTTPPath(w http.ResponseWriter, r *http.Request, p string)
}

type Renderer

type Renderer struct {
	BodyFs         http.FileSystem          // read body templates from here
	IncludeFs      http.FileSystem          // read included templates from here
	BodyTemplaters map[string]BodyTemplater // map of file extension to BodyTemplater
	PathExpandFunc func(string) []string    // translate a path into a list of other possible ones that should be checked (in sequence) and the first one found rendered
}

func NewDefaultRenderer

func NewDefaultRenderer(bodyFs http.FileSystem, includeFs http.FileSystem) *Renderer

NewDefaultRenderer creates a renderer with sensible defaults and supports Go templates and markdown.

func (*Renderer) ServeHTTP

func (rr *Renderer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

func (*Renderer) ServeHTTPPath

func (rr *Renderer) ServeHTTPPath(w http.ResponseWriter, r *http.Request, p string)

ServeHTTPPath implemented RenderHandler and is like ServeHTTP but lets you override which file it will look for. This is a simple way to "rewrite" URLs based on custom logic - you just call the Renderer with the appropriate custom path.

type ResponseWriterCloser

type ResponseWriterCloser interface {
	http.ResponseWriter
	io.Closer
}

func GzipCtxWrap

GzipCtxWrap returns a ResponseWriterCloser that implements gzip response writing if possible and a context that is cancelled once the response header is written. This makes it simple to ask the context if the request has been handled yet.

type StaticFileServer

type StaticFileServer struct {
	Fs  afero.Fs
	Dir string
}

StaticFileServer serves static files from a directory.

func NewStaticFileServer

func NewStaticFileServer(fs afero.Fs, dir string) *StaticFileServer

FIXME: this should be http.FileSystem - we don't need write functionality for static file serving...

func (*StaticFileServer) ServeHTTP

func (sfs *StaticFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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