beepboop

package module
v0.0.0-...-8f1460f Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2024 License: MIT Imports: 26 Imported by: 3

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrRateLimitExceeded = fmt.Errorf("rate limit exceeded")

ErrRateLimitExceeded ...

View Source
var TemplateFuncs = template.FuncMap{
	"TimeElapsed": func(then int64) string {
		return TimeElapsed(time.Now(), time.Unix(then, 0))
	},
	"ByteCountSI":  ByteCountSI,
	"ByteCountIEC": ByteCountIEC,
}

TemplateFuncs is beepboop's built in template FuncMap

Functions

func ByteCountIEC

func ByteCountIEC(b int64) string

ByteCountIEC ...

func ByteCountSI

func ByteCountSI(b int64) string

ByteCountSI ...

func GetBase

func GetBase(r *http.Request) string

GetBase returns the base target for relative URLs

func TimeElapsed

func TimeElapsed(now time.Time, then time.Time) string

TimeElapsed returns the elapsed time in human readable format (such as "5 days ago")

Types

type AccessCode

type AccessCode string

AccessCode is the code that proves the access is valid

type AccessMap

type AccessMap map[AccessType]map[AccessResourceName]AccessCode

AccessMap is the map of available accesses to various resources

func (AccessMap) Add

func (m AccessMap) Add(accessType, resource, code string)

Add adds access to a resource

func (AccessMap) Get

func (m AccessMap) Get(accessType, resource string) (string, bool)

Get gets the access code to a resource

func (AccessMap) Merge

func (m AccessMap) Merge(other AccessMap)

Merge merges an AccessMap into this AccessMap

func (AccessMap) Remove

func (m AccessMap) Remove(accessType, resource string)

Remove removes access to a resource

func (AccessMap) Revoke

func (m AccessMap) Revoke(revoke AccessRevokeMap, keep bool)

Revoke revokes access to resources from this AccessMap

func (AccessMap) ToCookies

func (m AccessMap) ToCookies(expiration time.Duration) []*http.Cookie

ToCookies returns a list of cookies containing access to the resources in the access token

type AccessResourceName

type AccessResourceName string

AccessResourceName is the name of the resource, like a user or a folder

type AccessRevokeMap

type AccessRevokeMap map[AccessType]AccessResourceName

AccessRevokeMap is used to ravoke access to various resources

type AccessType

type AccessType string

AccessType is the type of access, like 'read' or 'write'

type Context

type Context struct {
	Context context.Context

	DB               *DB
	Logger           *log.Logger
	GeoIPClient      geoip.Client
	Limiters         map[string]*RateLimiter
	Layout           Layout
	CookieExpiration time.Duration
	// contains filtered or unexported fields
}

Context ...

func (*Context) GetServiceLimiter

func (ctx *Context) GetServiceLimiter(service, ip string) *rate.Limiter

GetServiceLimiter returns the rate limiter for the given service and IP

type ContextGetter

type ContextGetter func(context.Context, Layout) *Context

ContextGetter ...

type DB

type DB struct {
	CacheDuration   time.Duration
	SessionDuration time.Duration
	// contains filtered or unexported fields
}

DB ...

func NewDB

func NewDB(redisUrl string) (*DB, error)

NewDB returns a new DB

func (*DB) CacheValue

func (db *DB) CacheValue(key string, value interface{}, rewriteExisting bool) error

CacheValue caches a value

func (*DB) GetCachedValue

func (db *DB) GetCachedValue(key string, value interface{}) error

GetCachedValue tries to unmarshal a cached value

func (*DB) IsWithinRateLimit

func (db *DB) IsWithinRateLimit(reqType, ip string, rate int) (bool, error)

IsWithinRateLimit returns whether a request is withing rate limit per minute

func (*DB) UncacheValue

func (db *DB) UncacheValue(key string) error

UncacheValue removes a cached value

type ErrorRenderer

type ErrorRenderer func(w http.ResponseWriter, r *http.Request, errmsg string, errcode int)

ErrorRenderer is a special kind of layout renderer to render an error

func GetErrorRenderer

func GetErrorRenderer(layout Layout) ErrorRenderer

GetErrorRenderer returns an ErrorRenderer using the given layout

type Layout

type Layout interface {
	BindTemplate(pageTemplate string, stylesheets, scripts []string, meta map[string]string) (LayoutRenderer, error)
}

Layout is used to give pages a uniform layout

var DefaultLayout Layout = (*layout)(template.Must(template.New("layout").Funcs(sprig.FuncMap()).Funcs(TemplateFuncs).Parse(layoutT)))

DefaultLayout is razlink's default layout

type LayoutRenderer

type LayoutRenderer func(w http.ResponseWriter, r *http.Request, title string, data interface{}, statusCode int)

LayoutRenderer is a function that renders a html page

type Middleware

type Middleware func(pr *PageRequest) *View

Middleware is a function called before a page handler to be able to change or intercept the request

type Page

type Page struct {
	Path            string
	Title           string
	ContentTemplate string
	Stylesheets     []string
	Scripts         []string
	Metadata        map[string]string
	Handler         func(*PageRequest) *View
	OnlyLogOnError  bool
}

Page ...

func FSPage

func FSPage(pagePath string, f fs.FS) *Page

FSPage returns a page that serves assets from fs.FS

func StaticAssetPage

func StaticAssetPage(pagePath, assetDir string) *Page

StaticAssetPage returns a page that serves static assets from a directory

func (*Page) GetAPIHandler

func (page *Page) GetAPIHandler(getctx ContextGetter) http.Handler

GetAPIHandler creates a http.Handler that handles API requests of the page

func (*Page) GetHandler

func (page *Page) GetHandler(layout Layout, getctx ContextGetter) (http.Handler, error)

GetHandler creates a http.Handler that uses the given layout to render the page

type PageRequest

type PageRequest struct {
	Context   *Context
	Request   *http.Request
	RequestID string
	RelPath   string
	RelURI    string
	PagePath  string
	Title     string
	IsAPI     bool
	// contains filtered or unexported fields
}

PageRequest ...

func (*PageRequest) AsyncCopyView

func (r *PageRequest) AsyncCopyView(resp *http.Response, opts ...ViewOption) *View

AsyncCopyView returns a View that copies the content of a http.Response asynchronously

func (*PageRequest) CopyView

func (r *PageRequest) CopyView(resp *http.Response, opts ...ViewOption) *View

CopyView returns a View that copies the content of a http.Response

func (*PageRequest) CustomErrorView

func (r *PageRequest) CustomErrorView(errmsg string, errcode int, renderer ErrorRenderer, opts ...ViewOption) *View

CustomErrorView returns a View that represents an error and uses a custom renderer

func (*PageRequest) EmbedView

func (r *PageRequest) EmbedView(url string, opts ...ViewOption) *View

EmbedView returns a View that embeds the given URL

func (*PageRequest) ErrorView

func (r *PageRequest) ErrorView(errmsg string, errcode int, opts ...ViewOption) *View

ErrorView returns a View that represents an error

func (*PageRequest) FileView

func (r *PageRequest) FileView(file http.File, mime string, attachment bool, opts ...ViewOption) *View

FileView returns a View that serves a file

func (*PageRequest) HandlerView

func (r *PageRequest) HandlerView(handler http.HandlerFunc, opts ...ViewOption) *View

HandlerView returns a View that uses a http.HandlerFunc to render a response

func (*PageRequest) Log

func (r *PageRequest) Log(a ...interface{})

Log ...

func (*PageRequest) Logf

func (r *PageRequest) Logf(format string, a ...interface{})

Logf ...

func (*PageRequest) RedirectView

func (r *PageRequest) RedirectView(url string, opts ...ViewOption) *View

RedirectView returns a View that redirects to the given URL

func (*PageRequest) Respond

func (r *PageRequest) Respond(data interface{}, opts ...ViewOption) *View

Respond returns the default page response View

func (*PageRequest) Session

func (r *PageRequest) Session() *Session

Session returns the current session

type RateLimiter

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

RateLimiter is a simple N/interval/IP rate limiter

func NewRateLimiter

func NewRateLimiter(interval time.Duration, n int) *RateLimiter

NewRateLimiter returns a new RateLimiter

func (*RateLimiter) Get

func (r *RateLimiter) Get(ip string) *rate.Limiter

Get returns the limiter state for the given IP

type Server

type Server struct {
	Layout           Layout
	FaviconPNG       []byte
	Header           http.Header
	Metadata         map[string]string
	DB               *DB
	Logger           *log.Logger
	GeoIPClient      geoip.Client
	Limiters         map[string]*RateLimiter
	Middlewares      []Middleware
	CookieExpiration time.Duration
	// contains filtered or unexported fields
}

Server ...

func NewServer

func NewServer() *Server

NewServer creates a new Server

func (*Server) AddMiddleware

func (srv *Server) AddMiddleware(middleware Middleware)

AddMiddleware adds a middleware

func (*Server) AddMiddlewares

func (srv *Server) AddMiddlewares(middlewares ...Middleware)

AddMiddlewares adds middlewares

func (*Server) AddPage

func (srv *Server) AddPage(page *Page) error

AddPage adds a new servable page to the server

func (*Server) AddPageWithLayout

func (srv *Server) AddPageWithLayout(page *Page, layout Layout) error

AddPageWithLayout adds a new servable page with custom layout to the server

func (*Server) AddPages

func (srv *Server) AddPages(pages ...*Page)

AddPages adds multiple pages to the server and panics if anything goes wrong

func (*Server) AddServiceRate

func (srv *Server) AddServiceRate(service string, interval time.Duration, n int)

AddServiceRate limit sets up a rate limiter for a given service name which can be used by page handlers and middlewares

func (*Server) ConnectDB

func (srv *Server) ConnectDB(redisUrl string) error

ConnectDB ...

func (*Server) ServeHTTP

func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Session

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

Session ...

func (*Session) AddAccess

func (sess *Session) AddAccess(accessType, resource, accesscode string) error

AddAccess permits the requester to access the given resource

func (*Session) Context

func (sess *Session) Context() context.Context

Context returns the context of the session

func (*Session) GetAccessCode

func (sess *Session) GetAccessCode(accessType, resource string) (string, bool)

GetAccessCode returns the access code to the given resource

func (*Session) IP

func (sess *Session) IP() string

IP returns the session IP address

func (*Session) MergeAccess

func (sess *Session) MergeAccess(access AccessMap) error

MergeAccess permits the requester to access the given resources

func (*Session) RemoveAccess

func (sess *Session) RemoveAccess(accessType, resource string) error

RemoveAccess removes the requester's access to the given resource

func (*Session) RevokeAccess

func (sess *Session) RevokeAccess(revoke AccessRevokeMap) error

RevokeAccess revokes the requester's access to the given resources

func (*Session) SessionID

func (sess *Session) SessionID() string

SessionID returns the sessionID

type View

type View struct {
	StatusCode int
	Error      error
	Data       interface{}
	Redirect   string
	// contains filtered or unexported fields
}

View is something that a PageHandler returns and is capable of rendering a page

func AsyncCopyView

func AsyncCopyView(resp *http.Response, opts ...ViewOption) *View

AsyncCopyView returns a View that copies the content of a http.Response asynchronously

func CopyView

func CopyView(resp *http.Response, opts ...ViewOption) *View

CopyView returns a View that copies the content of a http.Response

func CustomErrorView

func CustomErrorView(r *http.Request, errmsg string, errcode int, renderer ErrorRenderer, opts ...ViewOption) *View

CustomErrorView returns a View that represents an error and uses a custom renderer

func EmbedView

func EmbedView(url string, opts ...ViewOption) *View

EmbedView returns a View that embeds the given URL

func ErrorView

func ErrorView(r *http.Request, errmsg string, errcode int, opts ...ViewOption) *View

ErrorView returns a View that represents an error

func FileView

func FileView(r *http.Request, file http.File, mime string, attachment bool, opts ...ViewOption) *View

FileView returns a View that serves a file

func HandlerView

func HandlerView(r *http.Request, handler http.HandlerFunc, opts ...ViewOption) *View

HandlerView returns a View that uses a http.HandlerFunc to render a response

func RedirectView

func RedirectView(r *http.Request, url string, opts ...ViewOption) *View

RedirectView returns a View that redirects to the given URL

func (*View) Close

func (view *View) Close() error

Close frees resources used by the view

func (*View) Render

func (view *View) Render(w http.ResponseWriter)

Render renders the view

func (*View) RenderAPIResponse

func (view *View) RenderAPIResponse(w http.ResponseWriter)

RenderAPIResponse renders the API response of the view

type ViewOption

type ViewOption func(view *View)

ViewOption is used to customize the error message, error code or data in the view

func WithCookie

func WithCookie(cookie *http.Cookie) ViewOption

WithCookie adds a cookie to the view

func WithData

func WithData(data interface{}) ViewOption

WithData sets the view data

func WithError

func WithError(err error, errcode int) ViewOption

WithError sets the view error and error code

func WithErrorMessage

func WithErrorMessage(errmsg string, errcode int) ViewOption

WithErrorMessage sets the view error message and error code

func WithHeader

func WithHeader(key, value string) ViewOption

WithHeader adds a header field to the view

Directories

Path Synopsis
demo

Jump to

Keyboard shortcuts

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