ambient

package module
v0.0.0-...-545971b Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2022 License: MIT Imports: 14 Imported by: 74

README

Ambient core

GitHub Actions status

Thanks for visiting! All docs are available here.

This repository contains the code for the Ambient core which includes:

Documentation

Overview

Package ambient is a pluggable web app framework.

Index

Constants

View Source
const (
	// LocationHead is at the bottom of the HTML <head> section.
	LocationHead AssetLocation = "head"
	// LocationHeader is at the top the HTML <header> section.
	LocationHeader AssetLocation = "header"
	// LocationMain is at the bottom of the HTML <main> section.
	LocationMain AssetLocation = "main"
	// LocationFooter is in the HTML <footer> section.
	LocationFooter AssetLocation = "footer"
	// LocationBody is at the bottom of the HTML <body> section.
	LocationBody AssetLocation = "body"

	// AssetStylesheet is a stylesheet element.
	AssetStylesheet AssetType = "stylesheet"
	// AssetJavaScript is a javascript element.
	AssetJavaScript AssetType = "javascript"
	// AssetGeneric is a generic element.
	AssetGeneric AssetType = "generic"

	// AuthAll is both anonymous and authenticated users.
	AuthAll AuthType = "all" // Default.
	// AuthAnonymousOnly is only non-authenticated users.
	AuthAnonymousOnly AuthType = "anonymous"
	// AuthOnly is only authenticated users.
	AuthOnly AuthType = "authenticated"

	// LayoutPage is a page layout.
	LayoutPage LayoutType = "page"
	// LayoutPost is a post layout.
	LayoutPost LayoutType = "post"
)

Variables

This section is empty.

Functions

func AuthAssetAllowed

func AuthAssetAllowed(loggedIn bool, f Asset) bool

AuthAssetAllowed return true if the user has access to the asset.

func GlobalFuncMap

func GlobalFuncMap(fm template.FuncMap) template.FuncMap

GlobalFuncMap returns the FuncMaps available in all templates.

func SetupRouter

func SetupRouter(logger Logger, mux AppRouter, te Renderer, customServeHTTP CustomServeHTTP)

SetupRouter sets the router with the NotFound handler and the default handler.

func Validate

func Validate(p PluginCore) error

Validate returns an error if the plugin name or version is not valid.

Types

type AppLogger

type AppLogger interface {
	Logger

	// Fatal is reserved for the app level only.
	Fatal(format string, v ...interface{})
	SetLogLevel(level LogLevel)
	Named(name string) AppLogger
	Name() string
}

AppLogger represents the log service for the app.

type AppRouter

type AppRouter interface {
	Router

	ServeHTTP(w http.ResponseWriter, r *http.Request)
	SetNotFound(notFound http.Handler)
	SetServeHTTP(h func(w http.ResponseWriter, r *http.Request, err error))
}

AppRouter represents a router.

type AppSession

type AppSession interface {
	AuthenticatedUser(r *http.Request) (string, error)
	Login(r *http.Request, username string)
	Logout(r *http.Request)
	LogoutAll(r *http.Request) error
	Persist(r *http.Request, persist bool)
	SetCSRF(r *http.Request) string
	CSRF(r *http.Request, token string) bool
	SessionValue(r *http.Request, name string) string
	SetSessionValue(r *http.Request, name string, value string) error
	DeleteSessionValue(r *http.Request, name string)
}

AppSession represents a user session.

type Asset

type Asset struct {
	// Filetype is the type of asset: generic, stylesheet, or javascript. (required)
	Filetype AssetType `json:"filetype"`
	// Location is the location on the HTML page where the asset will be
	// added. (required)
	Location AssetLocation `json:"location"`
	// Auth determines whether to show the asset to all users, only authenticated
	// users, or only non-authenticated users. Will display to all users if
	// not specified. (optional)
	Auth AuthType `json:"auth"`
	// Attributes are a list of HTML attributes on all filetypes except on
	// generic with no TagName. (optional)
	Attributes []Attribute `json:"attributes"`
	// LayoutOnly are a list of layout types where the element will be added.
	// Supports page and post. Will display on all layouts if not specified.
	// (optional)
	LayoutOnly []LayoutType `json:"layout"`

	// TagName is only for generic assets when Inline is true. Will specify the
	// type of element to create. If empty, then the asset will be written to
	// the page without a surrounding HTML element.
	TagName string `json:"tagname"`
	// ClosingTag, if true, will add a closing tag. It's only for generic assets
	// when inline is false.
	ClosingTag bool `json:"closingtag"`

	// External, if true, will just use the path as the source of the element.
	// It is only for stylesheet and javascript filetypes.
	External bool `json:"external"`
	// Inline if true, will output the contents from an embedded file (Path) or
	// the contents (Content) after doing a find/replace (Replace).
	Inline bool `json:"inline"`
	// SkipExistCheck if true, will not check for the file existing because it's
	// managed by a route.
	SkipExistCheck bool `json:"skipexist"`
	// Path is relative path to the embedded file or the full path to the
	// external asset. (optional)
	Path string `json:"path"`
	// Content is the content that will output on the page. Path must be empty
	// for content to be used and content is only used when Inline is true.
	Content string `json:"content"`
	// Replace is a list of find and replace strings that are run on the Path
	// or Content when Inline is true.
	Replace []Replace `json:"replace"`
}

Asset represents an HTML asset like a stylesheet or javascript file.

func (*Asset) Contents

func (file *Asset) Contents(assets fs.FS) (ff []byte, status int, err error)

Contents returns the text of the file to inline in HTML after doing replace.

func (*Asset) Element

func (file *Asset) Element(logger AppLogger, v Plugin, assets fs.FS, debug bool) string

Element returns an HTML element.

func (Asset) Routable

func (file Asset) Routable() bool

Routable returns true if the file can be served from the embedded filesystem.

func (Asset) SanitizedPath

func (file Asset) SanitizedPath() string

SanitizedPath returns an HTML escaped asset path.

type AssetInjector

type AssetInjector interface {
	Inject(injector LayoutInjector, t *template.Template, r *http.Request, layoutType LayoutType, vars map[string]interface{}) (*template.Template, error)
	DebugTemplates() bool
	EscapeTemplates() bool
}

AssetInjector represents code that can inject files into a template.

type AssetLocation

type AssetLocation string

AssetLocation is a location where assets can be added.

type AssetType

type AssetType string

AssetType is a type of asset.

type Attribute

type Attribute struct {
	Name  string
	Value interface{}
}

Attribute represents an HTML attribute.

type AuthType

type AuthType string

AuthType is a type of authentication.

type CustomServeHTTP

type CustomServeHTTP func(log Logger, renderer Renderer,
	w http.ResponseWriter, r *http.Request, err error)

CustomServeHTTP allows customization of error handling by the router.

type DataStorer

type DataStorer interface {
	Save([]byte) error
	Load() ([]byte, error)
}

DataStorer reads and writes data to an object.

type Error

type Error interface {
	error
	Status() int
	Message() string
}

Error represents a handler error. It provides methods for a HTTP status code and embeds the built-in error interface.

type FileSystemReader

type FileSystemReader interface {
	Open(name string) (fs.File, error)
	ReadDir(name string) ([]fs.DirEntry, error)
	ReadFile(name string) ([]byte, error)
}

FileSystemReader can be used with embed.FS and avfs.FS.

type GRPCPluginBase

type GRPCPluginBase struct {
	PluginBase
	// contains filtered or unexported fields
}

GRPCPluginBase represents a base gRPC plugin that works with Ambient.

func NewGRPCPlugin

func NewGRPCPlugin(pluginName string, pluginPath string) *GRPCPluginBase

NewGRPCPlugin returns gRPC plugin base.

func (*GRPCPluginBase) PluginName

func (p *GRPCPluginBase) PluginName() string

PluginName returns the gRPC plugin name.

func (*GRPCPluginBase) PluginPath

func (p *GRPCPluginBase) PluginPath() string

PluginPath returns the gRPC plugin path.

func (*GRPCPluginBase) PluginVersion

func (p *GRPCPluginBase) PluginVersion() string

PluginVersion returns the gRPc text.

type GRPCSystem

type GRPCSystem interface {
	// Monitor starts monitoring the gRPC plugins.
	Monitor(securesite SecureSite)
	// ConnectAll will connect to all initial gRPC plugins in the plugin system.
	ConnectAll()
	// Connect will connect to a new gRPC plugin, these don't have to be in the
	// initial plugin loader.
	Connect(p Plugin, middleware bool)
	// Disconnect stops the gRPC clients.
	Disconnect()
}

GRPCSystem manages connecting, loading, monitoring, and disconnecting gRPC plugins..

type Grant

type Grant string

Grant is a type of permission.

const (
	// GrantSiteTitleRead allows read access to the site title.
	GrantSiteTitleRead Grant = "site.title:read"
	// GrantSiteTitleWrite allows write access to the site title.
	GrantSiteTitleWrite Grant = "site.title:write"
	// GrantSiteContentRead allows read access to the site content.
	GrantSiteContentRead Grant = "site.content:read"
	// GrantSiteContentWrite allows write access to the site content.
	GrantSiteContentWrite Grant = "site.content:write"
	// GrantSiteSchemeRead allows read access to the site scheme.
	GrantSiteSchemeRead Grant = "site.scheme:read"
	// GrantSiteSchemeWrite allows write access to the site scheme.
	GrantSiteSchemeWrite Grant = "site.scheme:write"
	// GrantSiteURLRead allows read access to the site URL.
	GrantSiteURLRead Grant = "site.url:read"
	// GrantSiteURLWrite allows write access to the site URL.
	GrantSiteURLWrite Grant = "site.url:write"
	// GrantSiteUpdatedRead allows read access to the site updated time.
	GrantSiteUpdatedRead Grant = "site.updated:read"

	// GrantSiteLoadTrigger allows trigger access to the site load from data storage.
	GrantSiteLoadTrigger Grant = "site.load:trigger"

	// GrantSitePostRead allows read access to the site posts.
	// Allows access to calls like: postsandpages, publishedpages, postbyslug, tags.
	GrantSitePostRead Grant = "site.post:read"
	// GrantSitePostWrite allows write access to the site posts.
	GrantSitePostWrite Grant = "site.post:write"
	// GrantSitePostDelete allows delete access to the site posts.
	GrantSitePostDelete Grant = "site.post:delete"

	// GrantSitePluginRead allows read access to the site plugins.
	GrantSitePluginRead Grant = "site.plugin:read"
	// GrantSitePluginEnable allows enable access to the site plugins.
	GrantSitePluginEnable Grant = "site.plugin:enable"
	// GrantSitePluginDisable allows disable access to the site plugins.
	GrantSitePluginDisable Grant = "site.plugin:disable"
	// GrantSitePluginDelete allows delete access to the site plugins.
	GrantSitePluginDelete Grant = "site.plugin:delete"

	// GrantRouterRouteWrite allows write access to routes.
	GrantRouterRouteWrite Grant = "router.route:write"
	// GrantRouterMiddlewareWrite allows adding middleware to routes.
	GrantRouterMiddlewareWrite Grant = "router.middleware:write"

	// GrantPluginSettingRead allows read access to the plugin setting.
	GrantPluginSettingRead Grant = "plugin.setting:read"
	// GrantPluginSettingWrite allows write access to the plugin setting.
	GrantPluginSettingWrite Grant = "plugin.setting:write"
	// GrantPluginNeighborSettingRead allows read access to a setting in another plugin.
	GrantPluginNeighborSettingRead Grant = "plugin.neighborsetting:read"
	// GrantPluginNeighborSettingWrite allows write access to a setting in another plugin.
	GrantPluginNeighborSettingWrite Grant = "plugin.neighborsetting:write"
	// GrantPluginNeighborGrantRead allows read access to a grant in another plugin.
	GrantPluginNeighborGrantRead Grant = "plugin.neighborgrant:read"
	// GrantPluginNeighborGrantWrite allows write access to a grant in another plugin.
	GrantPluginNeighborGrantWrite Grant = "plugin.neighborgrant:write"
	// GrantPluginTrustedRead allows read access to whether a plugin is trusted or not.
	GrantPluginTrustedRead Grant = "plugin.trusted:read"
	// GrantPluginNeighborRouteRead allows read access to routes in another plugin.
	GrantPluginNeighborRouteRead Grant = "plugin.neighborroute:read"

	// GrantUserAuthenticatedRead allows read access whether the current user is logged in or not.
	GrantUserAuthenticatedRead Grant = "user.authenticated:read"
	// GrantUserAuthenticatedWrite allows write access to login or logout a user.
	GrantUserAuthenticatedWrite Grant = "user.authenticated:write"
	// GrantUserPersistWrite allows write access to login or logout a user.
	GrantUserPersistWrite Grant = "user.persist:write"
	// GrantAllUserAuthenticatedWrite allows write access to login or logout any user.
	GrantAllUserAuthenticatedWrite Grant = "alluser.authenticated:write"

	// GrantSiteAssetWrite allows write access to site assets.
	GrantSiteAssetWrite Grant = "site.asset:write"
	// GrantSiteFuncMapWrite allows write access to site FuncMap for templates.
	GrantSiteFuncMapWrite Grant = "site.funcmap:write"
)

type GrantRequest

type GrantRequest struct {
	Grant       Grant
	Description string
}

GrantRequest represents a plugin grant request.

type LayoutInjector

type LayoutInjector interface {
	Head(t *template.Template, content string, fm template.FuncMap, data map[string]interface{}) (*template.Template, error)
	Header(t *template.Template, content string, fm template.FuncMap, data map[string]interface{}) (*template.Template, error)
	Main(t *template.Template, content string, fm template.FuncMap, data map[string]interface{}) (*template.Template, error)
	Footer(t *template.Template, content string, fm template.FuncMap, data map[string]interface{}) (*template.Template, error)
	Body(t *template.Template, content string, fm template.FuncMap, data map[string]interface{}) (*template.Template, error)
}

LayoutInjector represents an injector that the AssetInjector will call to inject assets in the correct place.

type LayoutType

type LayoutType string

LayoutType is a type of layout.

type LogLevel

type LogLevel int

LogLevel is a log level.

const (
	// LogLevelDebug is for debugging output. It's very verbose.
	LogLevelDebug LogLevel = iota
	// LogLevelInfo is for informational messages. It shows messages on services
	// starting, stopping, and users logging in.
	LogLevelInfo
	// LogLevelWarn is for behavior that may need to be fixed. It shows
	// permission warnings for plugins.
	LogLevelWarn
	// LogLevelError is for messages when something is wrong with the
	// app and it needs to be corrected.
	LogLevelError
	// LogLevelFatal is for messages when the app cannot continue and
	// will halt.
	LogLevelFatal
)

func EnvLogLevel

func EnvLogLevel() LogLevel

EnvLogLevel returns the log level from the AMB_LOGLEVEL environment variable.

type Logger

type Logger interface {
	Log(level LogLevel, format string, v ...interface{})
	Debug(format string, v ...interface{})
	Info(format string, v ...interface{})
	Warn(format string, v ...interface{})
	Error(format string, v ...interface{})
}

Logger represents the log service for the plugins.

type LoggingPlugin

type LoggingPlugin interface {
	PluginCore

	Logger(appName string, appVersion string, writer io.Writer) (AppLogger, error)
}

LoggingPlugin represents a logging plugin.

type MiddlewarePlugin

type MiddlewarePlugin interface {
	Plugin

	Middleware() []func(next http.Handler) http.Handler // optional, called during enable
}

MiddlewarePlugin represents a middleware plugin.

type Plugin

type Plugin interface {
	PluginCore

	// These should all have access to the toolkit.
	Enable(*Toolkit) error                           // optional, called during enable
	Disable() error                                  // optional, called during disable
	Routes()                                         // optional, called during enable
	Assets() ([]Asset, FileSystemReader)             // optional, called during enable
	Settings() []Setting                             // optional, called during special operations
	GrantRequests() []GrantRequest                   // optional, called during every plugin operation against data provider
	FuncMap() func(r *http.Request) template.FuncMap // optional, called on every render
}

Plugin represents a plugin.

type PluginBase

type PluginBase struct {
	*Toolkit
}

PluginBase represents a base plugin that works with Ambient.

func (*PluginBase) Assets

func (p *PluginBase) Assets() ([]Asset, FileSystemReader)

Assets returns a list of assets and an embedded filesystem.

func (*PluginBase) Disable

func (p *PluginBase) Disable() error

Disable is to disable the plugin.

func (*PluginBase) Enable

func (p *PluginBase) Enable(toolkit *Toolkit) error

Enable is to enable the plugin. Toolkit should be saved.

func (*PluginBase) FuncMap

func (p *PluginBase) FuncMap() func(r *http.Request) template.FuncMap

FuncMap returns a callable function that accepts a request.

func (*PluginBase) GrantRequests

func (p *PluginBase) GrantRequests() []GrantRequest

GrantRequests returns a list of grants requested by the plugin.

func (*PluginBase) Middleware

func (p *PluginBase) Middleware() []func(next http.Handler) http.Handler

Middleware returns a list of middleware.

func (*PluginBase) Routes

func (p *PluginBase) Routes()

Routes sets routes for the plugin.

func (*PluginBase) Settings

func (p *PluginBase) Settings() []Setting

Settings returns a list of user settable fields.

type PluginCore

type PluginCore interface {
	// PluginName should be globally unique. It must start with a lowercase
	// letter and then contain only lowercase letters and numbers.
	PluginName() string
	// PluginVersion must follow https://semver.org/.
	PluginVersion() string
}

PluginCore represents the core of any plugin.

type PluginData

type PluginData struct {
	Enabled  bool           `json:"enabled"`
	Version  string         `json:"version"`
	Grants   PluginGrants   `json:"grants"`
	Settings PluginSettings `json:"settings"`
}

PluginData represents the plugin storage information.

type PluginGrants

type PluginGrants map[Grant]bool

PluginGrants represents an unordered map of grants.

type PluginLoader

type PluginLoader struct {
	Router         RouterPlugin
	TemplateEngine TemplateEnginePlugin
	SessionManager SessionManagerPlugin
	TrustedPlugins map[string]bool
	Plugins        []Plugin
	Middleware     []MiddlewarePlugin
}

PluginLoader contains the plugins for the Ambient app.

type PluginSettings

type PluginSettings map[string]interface{}

PluginSettings represents an unordered map of settings.

type PluginSystem

type PluginSystem interface {
	// LoaderPlugins returns the loader plugins, these include initial gRPC plugins
	// as well.
	LoaderPlugins() []Plugin
	// LoaderMiddleware returns the loader middleware, these include initial gRPC plugins
	// as well.
	LoaderMiddleware() []MiddlewarePlugin
	// Plugins returns the map of plugins. This returns a map that is passed by
	// reference and all the values are pointers so any changes to it will
	// be reflected in the plugin system.
	Plugins() map[string]Plugin
	// SessionManager returns the session manager.
	SessionManager() SessionManagerPlugin
	// TemplateEngine returns the template engine.
	TemplateEngine() TemplateEnginePlugin
	// Router returns the router.
	Router() RouterPlugin
	// StorageManager returns the storage manager.
	StorageManager() Storage
	// LoadPlugin loads a single plugin into the plugin system and saves the config.
	LoadPlugin(plugin Plugin, middleware bool, grpcPlugin bool) (err error)
	// Load will load the storage and return an error if one occurs.
	Load() error
	// Save will save the storage and return an error if one occurs.
	Save() error
	// InitializePlugin will initialize the plugin in the storage and will return
	// an error if one occurs.
	InitializePlugin(pluginName string, pluginVersion string) error
	// RemovePlugin will delete the plugin from the storage and will return
	// an error if one occurs.
	RemovePlugin(pluginName string) error
	// Names returns a list of plugin names.
	Names() []string
	// MiddlewareNames returns a list of middleware plugin names.
	MiddlewareNames() []string
	// IsMiddleware returns if the plugin is middleware.
	IsMiddleware(name string) bool
	// TrustedPluginNames returns a list of sorted trusted names.
	TrustedPluginNames() []string
	// Trusted returns if a plugin is trusted.
	Trusted(pluginName string) bool
	// Routes returns a list of plugin routes.
	Routes(pluginName string) []Route
	// PluginsData returns the plugin data map.
	PluginsData() map[string]PluginData
	// Plugin returns a plugin by name.
	Plugin(name string) (Plugin, error)
	// PluginData returns a plugin data by name.
	PluginData(name string) (PluginData, error)
	// Enabled returns if the plugin is enabled or not. If it cannot be found, it
	// will still return false.
	Enabled(name string) bool
	// SetEnabled sets a plugin as enabled or not.
	SetEnabled(pluginName string, enabled bool) error
	// GrantRequests returns a list of grant requests.
	GrantRequests(pluginName string, grant Grant) ([]GrantRequest, error)
	// Authorized returns whether a plugin is inherited granted for a plugin.
	Authorized(pluginName string, grant Grant) bool
	// Granted returns whether a plugin is explicitly granted for a plugin.
	Granted(pluginName string, grant Grant) bool
	// SetGrant sets a plugin grant.
	SetGrant(pluginName string, grant Grant) error
	// RemoveGrant removes a plugin grant.
	RemoveGrant(pluginName string, grant Grant) error
	// SetSetting sets a plugin setting.
	SetSetting(pluginName string, settingName string, value interface{}) error
	// Setting returns a setting value.
	Setting(pluginName string, settingName string) (interface{}, error)
	// SettingDefault returns a setting default for a setting.
	SettingDefault(pluginName string, settingName string) (interface{}, error)
	// SetRoute saves a route.
	SetRoute(pluginName string, route []Route)
	// SetTitle sets the title.
	SetTitle(title string) error
	// Title returns the title.
	Title() string
	// SetScheme sets the site scheme.
	SetScheme(scheme string) error
	// Scheme returns the site scheme.
	Scheme() string
	// SetURL sets the site URL.
	SetURL(URL string) error
	// URL returns the URL without the scheme at the beginning.
	URL() string
	// FullURL returns the URL with the scheme at the beginning.
	FullURL() string
	// Updated returns the home last updated timestamp.
	Updated() time.Time
	// Tags returns the list of tags.
	Tags(onlyPublished bool) TagList
	// SetContent sets the home page content.
	SetContent(content string) error
	// Content returns the site home page content.
	Content() string
	// SavePost saves a post.
	SavePost(ID string, post Post) error
	// PostsAndPages returns the list of posts and pages.
	PostsAndPages(onlyPublished bool) PostWithIDList
	// PublishedPosts returns the list of published posts.
	PublishedPosts() []Post
	// PublishedPages returns the list of published pages.
	PublishedPages() []Post
	// PostBySlug returns the post by slug.
	PostBySlug(slug string) PostWithID
	// PostByID returns the post by ID.
	PostByID(ID string) (Post, error)
	// DeletePostByID deletes a post.
	DeletePostByID(ID string) error
}

PluginSystem provides config functions.

type Post

type Post struct {
	Title     string    `json:"title"`
	URL       string    `json:"url"`
	Canonical string    `json:"canonical"`
	Created   time.Time `json:"created"`
	Updated   time.Time `json:"updated"`
	Timestamp time.Time `json:"timestamp"`
	Content   string    `json:"content"`
	Published bool      `json:"published"`
	Page      bool      `json:"page"`
	Tags      TagList   `json:"tags"`
}

Post -

type PostList

type PostList []Post

PostList -

func (PostList) Len

func (t PostList) Len() int

func (PostList) Less

func (t PostList) Less(i, j int) bool

func (PostList) Swap

func (t PostList) Swap(i, j int)

type PostWithID

type PostWithID struct {
	Post
	ID string `json:"id"`
}

PostWithID -

type PostWithIDList

type PostWithIDList []PostWithID

PostWithIDList -

func (PostWithIDList) Len

func (t PostWithIDList) Len() int

func (PostWithIDList) Less

func (t PostWithIDList) Less(i, j int) bool

func (PostWithIDList) Swap

func (t PostWithIDList) Swap(i, j int)

type Renderer

type Renderer interface {
	Page(w http.ResponseWriter, r *http.Request, assets FileSystemReader, templateName string,
		fm func(r *http.Request) template.FuncMap, vars map[string]interface{}) (err error)
	PageContent(w http.ResponseWriter, r *http.Request, content string,
		fm func(r *http.Request) template.FuncMap, vars map[string]interface{}) (err error)
	Post(w http.ResponseWriter, r *http.Request, assets FileSystemReader, templateName string,
		fm func(r *http.Request) template.FuncMap, vars map[string]interface{}) (err error)
	PostContent(w http.ResponseWriter, r *http.Request, content string,
		fm func(r *http.Request) template.FuncMap, vars map[string]interface{}) (err error)
	Error(w http.ResponseWriter, r *http.Request, content string, statusCode int,
		fm func(r *http.Request) template.FuncMap, vars map[string]interface{}) (err error)
}

Renderer represents a template renderer.

type Replace

type Replace struct {
	Find    string
	Replace string
}

Replace represents text to find and replace.

type Route

type Route struct {
	Method string
	Path   string
}

Route is a route for a router.

type Router

type Router interface {
	Handle(method string, path string, fn func(http.ResponseWriter, *http.Request) error)
	Get(path string, fn func(http.ResponseWriter, *http.Request) error)
	Post(path string, fn func(http.ResponseWriter, *http.Request) error)
	Patch(path string, fn func(http.ResponseWriter, *http.Request) error)
	Put(path string, fn func(http.ResponseWriter, *http.Request) error)
	Delete(path string, fn func(http.ResponseWriter, *http.Request) error)
	Head(path string, fn func(http.ResponseWriter, *http.Request) error)
	Options(path string, fn func(http.ResponseWriter, *http.Request) error)
	StatusError(status int, err error) error
	Error(status int, w http.ResponseWriter, r *http.Request)
	Param(r *http.Request, name string) string
	Wrap(handler http.HandlerFunc) func(w http.ResponseWriter, r *http.Request) (err error)
}

Router represents a router.

type RouterPlugin

type RouterPlugin interface {
	PluginCore

	Router(logger Logger, render Renderer) (AppRouter, error)
}

RouterPlugin represents a router engine plugin.

type SecureSite

type SecureSite interface {
	// Error handles returning the proper error.
	Error(siteError error) (err error)
	// Load forces a reload of the data.
	Load() error
	// Authorized determines if the current context has access.
	Authorized(grant Grant) bool
	// NeighborPluginGrantList gets the grants requests for a neighbor plugin.
	NeighborPluginGrantList(pluginName string) ([]GrantRequest, error)
	// NeighborPluginGrants gets the map of granted permissions.
	NeighborPluginGrants(pluginName string) (map[Grant]bool, error)
	// NeighborPluginGranted returns true if the plugin has the grant.
	NeighborPluginGranted(pluginName string, grantName Grant) (bool, error)
	// NeighborPluginRequestedGrant returns true if the plugin requests the grant.
	// This shouldn't be used to determine if a plugin has been approved the grant.
	NeighborPluginRequestedGrant(pluginName string, grantName Grant) (bool, error)
	// SetNeighborPluginGrant sets a grant for a neighbor plugin.
	SetNeighborPluginGrant(pluginName string, grantName Grant, granted bool) error
	// Plugins returns the plugin list.
	Plugins() (map[string]PluginData, error)
	// PluginNames returns the list of plugin name.
	PluginNames() ([]string, error)
	// DeletePlugin deletes a plugin.
	DeletePlugin(name string) error
	// EnablePlugin enables a plugin.
	EnablePlugin(pluginName string, loadPlugin bool) error
	// LoadSinglePluginPages loads the plugin.
	LoadSinglePluginPages(name string)
	// DisablePlugin disables a plugin.
	DisablePlugin(pluginName string, unloadPlugin bool) error
	// SavePost saves a post.
	SavePost(ID string, post Post) error
	// PostsAndPages returns the list of posts and pages.
	PostsAndPages(onlyPublished bool) (PostWithIDList, error)
	// PublishedPosts returns the list of published posts.
	PublishedPosts() ([]Post, error)
	// PublishedPages returns the list of published pages.
	PublishedPages() ([]Post, error)
	// PostBySlug returns the post by slug.
	PostBySlug(slug string) (PostWithID, error)
	// PostByID returns the post by ID.
	PostByID(ID string) (Post, error)
	// DeletePostByID deletes a post.
	DeletePostByID(ID string) error
	// PluginNeighborRoutesList gets the routes for a neighbor plugin.
	PluginNeighborRoutesList(pluginName string) ([]Route, error)
	// AuthenticatedUser returns if the current user is authenticated.
	AuthenticatedUser(r *http.Request) (string, error)
	// UserLogin sets the current user as authenticated.
	UserLogin(r *http.Request, username string) error
	// UserPersist sets the user session to retain after browser close.
	UserPersist(r *http.Request, persist bool) error
	// UserLogout logs out the current user.
	UserLogout(r *http.Request) error
	// LogoutAllUsers logs out all users.
	LogoutAllUsers(r *http.Request) error
	// SetCSRF sets the session with a token and returns the token for use in a form
	// or header.
	SetCSRF(r *http.Request) string
	// CSRF returns true if the CSRF token is valid.
	CSRF(r *http.Request, token string) bool
	// SessionValue returns session value by name.
	SessionValue(r *http.Request, name string) string
	// SetSessionValue sets a value on the current session.
	SetSessionValue(r *http.Request, name string, value string) error
	// DeleteSessionValue deletes a session value on the current session.
	DeleteSessionValue(r *http.Request, name string)
	// PluginNeighborSettingsList gets the grants requests for a neighbor plugin.
	PluginNeighborSettingsList(pluginName string) ([]Setting, error)
	// SetPluginSetting sets a variable for the plugin.
	SetPluginSetting(settingName string, value string) error
	// PluginSettingBool returns a plugin setting as a bool.
	PluginSettingBool(name string) (bool, error)
	// PluginSettingString returns a setting for the plugin as a string.
	PluginSettingString(fieldName string) (string, error)
	// PluginSetting returns a setting for the plugin as an interface{}.
	PluginSetting(fieldName string) (interface{}, error)
	// SetNeighborPluginSetting sets a setting for a neighbor plugin.
	SetNeighborPluginSetting(pluginName string, settingName string, value string) error
	// NeighborPluginSettingString returns a setting for a neighbor plugin as a string.
	NeighborPluginSettingString(pluginName string, fieldName string) (string, error)
	// NeighborPluginSetting returns a setting for a neighbor plugin as an interface{}.
	NeighborPluginSetting(pluginName string, fieldName string) (interface{}, error)
	// PluginTrusted returns whether a plugin is trusted or not.
	PluginTrusted(pluginName string) (bool, error)
	// SetTitle sets the title.
	SetTitle(title string) error
	// Title returns the title.
	Title() (string, error)
	// SetScheme sets the site scheme.
	SetScheme(scheme string) error
	// Scheme returns the site scheme.
	Scheme() (string, error)
	// SetURL sets the site URL.
	SetURL(URL string) error
	// URL returns the URL without the scheme at the beginning.
	URL() (string, error)
	// FullURL returns the URL with the scheme at the beginning.
	FullURL() (string, error)
	// Updated returns the home last updated timestamp.
	Updated() (time.Time, error)
	// SetContent sets the home page content.
	SetContent(content string) error
	// Content returns the site home page content.
	Content() (string, error)
	// Tags returns the list of tags.
	Tags(onlyPublished bool) (TagList, error)
}

SecureSite provides plugin functions.

type SessionManagerPlugin

type SessionManagerPlugin interface {
	PluginCore

	// Session manager should have middleware with it.
	SessionManager(logger Logger, sessionStorer SessionStorer) (AppSession, error)
	Middleware() []func(next http.Handler) http.Handler
}

SessionManagerPlugin represents a session manager plugin.

type SessionStorer

type SessionStorer interface {
	Save([]byte) error
	Load() ([]byte, error)
}

SessionStorer reads and writes data to an object.

type Setting

type Setting struct {
	Name        string             `json:"name"`
	Type        SettingType        `json:"type"`
	Description SettingDescription `json:"description"`
	Hide        bool               `json:"hide"`
	Default     interface{}        `json:"default"`
}

Setting is a plugin settable field.

type SettingDescription

type SettingDescription struct {
	Text string `json:"text"`
	URL  string `json:"url"`
}

SettingDescription is a type of description.

type SettingType

type SettingType string

SettingType is an HTML type of setting.

const (
	// Input is a standard text field.
	Input SettingType = "input"
	// InputPassword is a standard password field.
	InputPassword SettingType = "password"
	// Textarea is a textarea field.
	Textarea SettingType = "textarea"
	// Checkbox is a checkbox field.
	Checkbox SettingType = "checkbox"
)

type Site

type Site struct {
	Title         string                `json:"title"`   // Title of the site.
	Content       string                `json:"content"` // Home or default content.
	Scheme        string                `json:"scheme"`  // http or https
	URL           string                `json:"url"`     // URL without scheme and without trailing slash.
	Updated       time.Time             `json:"updated"` // Save time the data was saved (not only changed).
	Posts         map[string]Post       `json:"posts"`   // List of posts.
	PluginStorage map[string]PluginData `json:"plugins"` // List of plugins, whether they are found, enabled, and what fields they support.
}

Site represents the site information that is in storage.

func (*Site) Correct

func (s *Site) Correct()

Correct will fill in the missing defaults.

func (Site) PostBySlug

func (s Site) PostBySlug(slug string) PostWithID

PostBySlug returns a post by slug/URL.

func (Site) PostsAndPages

func (s Site) PostsAndPages(onlyPublished bool) PostWithIDList

PostsAndPages returns list of posts and pages with IDs.

func (Site) PublishedPages

func (s Site) PublishedPages() []Post

PublishedPages returns published pages (no posts).

func (Site) PublishedPosts

func (s Site) PublishedPosts() []Post

PublishedPosts returns published posts (no pages).

func (Site) SiteURL

func (s Site) SiteURL() string

SiteURL returns the URL with the scheme.

func (Site) Tags

func (s Site) Tags(onlyPublished bool) TagList

Tags returns a list of tags.

type StatusError

type StatusError struct {
	Code     int
	Err      error
	Friendly string
}

StatusError represents an error with an associated HTTP status code.

func (StatusError) Error

func (se StatusError) Error() string

Error returns the error.

func (StatusError) Message

func (se StatusError) Message() string

Message returns a optional user friendly error message.

func (StatusError) Status

func (se StatusError) Status() int

Status returns a HTTP status code.

type Storage

type Storage interface {
	// Save writes the site object to the data storage and returns an error if it
	// cannot be written.
	Save() error
	// SaveDecrypted writes the site object to the data storage always decrypted and
	// returns an error if it cannot be written.
	SaveDecrypted() error
	// Load reads the site object from the data storage and returns an error if
	// it cannot be read.
	Load() error
	// LoadDecrypted reads the site object from the data storage always decrypted
	// and returns an error if it cannot be read.
	LoadDecrypted() error
}

Storage provides app config functions.

type StorageEncryption

type StorageEncryption interface {
	Encrypt(data []byte) ([]byte, error)
	Decrypt(enc []byte) ([]byte, error)
}

StorageEncryption represents a encryption/decryption for a storage plugin.

type StoragePlugin

type StoragePlugin interface {
	PluginCore

	Storage(logger Logger) (DataStorer, SessionStorer, error)
}

StoragePlugin represents a storage plugin.

type StoragePluginGroup

type StoragePluginGroup struct {
	Storage    StoragePlugin
	Encryption StorageEncryption
}

StoragePluginGroup represents a storage plugin and an optional encryption package.

type Tag

type Tag struct {
	Name      string    `json:"name"`
	Timestamp time.Time `json:"timestamp"`
}

Tag represents a tag on a post or page.

type TagList

type TagList []Tag

TagList represents a list of sortable tags.

func (TagList) Len

func (t TagList) Len() int

func (TagList) Less

func (t TagList) Less(i, j int) bool

func (TagList) Split

func (t TagList) Split(s string) TagList

Split returns a list of tags from a comma separated list.

func (TagList) String

func (t TagList) String() string

String returns a comma separated list of tags.

func (TagList) Swap

func (t TagList) Swap(i, j int)

type TemplateEnginePlugin

type TemplateEnginePlugin interface {
	PluginCore

	TemplateEngine(logger Logger, injector AssetInjector) (Renderer, error)
}

TemplateEnginePlugin represents a template engine plugin.

type Toolkit

type Toolkit struct {
	Log    Logger
	Mux    Router
	Render Renderer
	Site   SecureSite
}

Toolkit provides utilities to plugins.

func (*Toolkit) JSON

func (t *Toolkit) JSON(w http.ResponseWriter, status int, response interface{}) error

JSON sends a JSON response that is marshalable.

func (*Toolkit) JSONPretty

func (t *Toolkit) JSONPretty(w http.ResponseWriter, status int, response interface{}) error

JSONPretty sends an indented JSON response that is marshalable.

func (*Toolkit) Path

func (t *Toolkit) Path(url string) string

Path to a page with the proper URL prefix.

func (*Toolkit) Redirect

func (t *Toolkit) Redirect(w http.ResponseWriter, r *http.Request, url string, code int)

Redirect to a relative page with the proper URL prefix.

Directories

Path Synopsis
internal
grpcsystem
Package grpcsystem manages connecting, loading, monitoring, and disconnecting of gRPC plugins.
Package grpcsystem manages connecting, loading, monitoring, and disconnecting of gRPC plugins.
secureconfig
Package secureconfig provides the plugin with a secure API to interact with Ambient.
Package secureconfig provides the plugin with a secure API to interact with Ambient.
pkg
amberror
Package amberror has shared errors across the application.
Package amberror has shared errors across the application.
envdetect
Package envdetect detects in which cloud an app is running based on environment variables.
Package envdetect detects in which cloud an app is running based on environment variables.
grpcp
Package grpcp contains shared data between the host and plugins.
Package grpcp contains shared data between the host and plugins.
requestclient
Package requestclient provides HTTP request sending using JSON structs.
Package requestclient provides HTTP request sending using JSON structs.

Jump to

Keyboard shortcuts

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