Documentation
¶
Overview ¶
Package templating provides a high-performance, filesystem-based Go template engine. It is designed for generating dynamic, complex, and plausible-looking web content with minimal server overhead.
It includes a rich library of custom template functions for generating everything from structured data (JSON, forms) and styled elements (CSS, SVGs) to thematic text via an integrated, SQLite-backed Markov generator. The engine is fully configurable with safety limits to prevent abuse and supports hot-reloading of templates from the filesystem, enabling easy updates post-deployment.
For a complete list of template functions and usage examples, see the README.md file.
Index ¶
- func InitWordList(path string) error
- type DefinitionData
- type StyleBlock
- type TemplateConfig
- type TemplateManager
- func (tm *TemplateManager) Execute(w io.Writer, name string, data interface{}) error
- func (tm *TemplateManager) ExecuteTemplateString(w io.Writer, content string, data interface{}) error
- func (tm *TemplateManager) GetConfig() TemplateConfig
- func (tm *TemplateManager) GetRandomTemplate() string
- func (tm *TemplateManager) GetTemplateDir() string
- func (tm *TemplateManager) GetTemplateNames() []string
- func (tm *TemplateManager) Refresh() error
- func (tm *TemplateManager) SetConfig(config *TemplateConfig)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func InitWordList ¶
InitWordList loads the global dictionary of words from a file at the given path. It is designed to be called once at application startup. It uses a sync.Once to ensure the word list is loaded only a single time, making subsequent calls a no-op. An error is returned if the file cannot be read.
Types ¶
type DefinitionData ¶
DefinitionData is a simple struct to hold a term and its definition. It is used by the randomDefinitionData template function to return a slice that templates can easily range over to build definition lists (<dl>).
type StyleBlock ¶
type StyleBlock struct {
// Style contains the full <style>...</style> block as safe HTML.
Style template.HTML
// Class contains the unique CSS class name (e.g., "c-a1b2c3d4") to be used
// in an element's class attribute.
Class template.CSS
}
StyleBlock is a struct returned by the randomStyleBlock template function. It allows the template to access both the generated <style> block HTML and the unique parent class name required to apply those styles to a specific element.
type TemplateConfig ¶
type TemplateConfig struct {
// MarkovEnabled controls whether the `markov` template functions will use the
// markov generator for content generation. If false, they fall back to using
// the `random` functions.
MarkovEnabled bool `json:"markov_enabled"`
// MarkovSeparator sets the separator to be used by the markov tokenizer. (optional)
MarkovSeparator string `json:"markov_separator"`
// MarkovEoc sets the eoc to be used by the markov tokenizer. (optional)
MarkovEoc string `json:"markov_eoc"`
// MarkovSplitRegex sets the regex to be used by the markov tokenizer for splitting tokens. (optional)
MarkovSplitRegex string `json:"markov_split_regex"`
// MarkovEocRegex sets the regex to be used by the markov tokenizer for detecting EOC tokens. (optional)
MarkovEocRegex string `json:"markov_eoc_regex"`
// MarkovSeparatorExcRegex sets the regex to be used by the markov tokenizer for determining which tokens should
// not have a separator put in front of them. (optional)
MarkovSeparatorExcRegex string `json:"markov_separator_exc_regex"`
// MarkovEocExcRegex sets the regex to be used by the markov tokenizer for determining which tokens should not
// have an EOC token put after them. (optional)
MarkovEocExcRegex string `json:"markov_eoc_exc_regex"`
// PathWhitelist is a list of URL paths that are considered safe and should not
// be used for randomly generated links (e.g., "/api", "/admin"). This prevents
// collisions with real application endpoints.
PathWhitelist []string `json:"path_whitelist"`
// MinSubpaths defines the minimum number of segments in a generated URL path.
MinSubpaths int `json:"min_subpaths"`
// MaxSubpaths defines the maximum number of segments in a generated URL path.
MaxSubpaths int `json:"max_subpaths"`
// MaxJSONDepth sets a hard upper limit on the recursion depth for the randomJSON function.
MaxJSONDepth int `json:"max_json_depth"`
// MaxNestDivs sets a hard upper limit on the recursion depth for the nestDivs function.
// This prevents templates from requesting a depth that could crash a browser.
MaxNestDivs int `json:"max_nest_divs"`
// MaxTableRows sets the maximum number of rows for the randomComplexTable function.
MaxTableRows int `json:"max_table_rows"`
// MaxTableCols sets the maximum number of columns for the randomComplexTable function.
MaxTableCols int `json:"max_table_cols"`
// MaxFormFields sets the maximum number of fields for the randomForm function.
MaxFormFields int `json:"max_form_fields"`
// MaxStyleRules sets the maximum number of complex CSS rules generated by the
// randomStyleBlock function.
MaxStyleRules int `json:"max_style_rules"`
// MaxCssVars sets the maximum number of interdependent CSS custom properties
// generated by the randomCSSVars function.
MaxCssVars int `json:"max_css_vars"`
// MaxSvgElements sets a general limit for the complexity of generated SVGs,
// such as the recursion depth for fractals or the number of filter primitives.
MaxSvgElements int `json:"max_svg_elements"`
// MaxJsContentSize sets the maximum size in bytes of the content to be encoded
// and rendered by the jsInteractiveContent function.
MaxJsContentSize int `json:"max_js_content_size"`
// MaxJsWasteCycles sets the maximum number of iterations for the CPU waste
// loop within the jsInteractiveContent function.
MaxJsWasteCycles int `json:"max_js_waste_cycles"`
}
TemplateConfig holds all configuration options for the templating engine. It provides granular control over the generated content, including safety limits for computationally expensive functions to prevent abuse and ensure stability for both the server and the client's browser.
func DefaultConfig ¶
func DefaultConfig() *TemplateConfig
DefaultConfig returns a new TemplateConfig populated with safe, sensible default values. The PathWhitelist is empty by default, assuming that any non-API path will serve tarpit content.
type TemplateManager ¶
type TemplateManager struct {
// contains filtered or unexported fields
}
TemplateManager is the central controller for the templating engine. It manages the template set, configuration, function map, and connections to other services like the Markov generator. It is responsible for loading, parsing, and executing templates in a concurrent-safe manner. All methods are concurrent-safe.
func NewTemplateManager ¶
func NewTemplateManager(logger *slog.Logger, markovGen *markov.Generator, config *TemplateConfig, dataDir string) (*TemplateManager, error)
NewTemplateManager creates, initializes, and returns a new TemplateManager. It requires a logger, an optional Markov generator (can be nil if config.MarkovEnabled is false), a configuration, and the path to the data directory which must contain a "templates" subdirectory and a "wordlist.txt" file. It performs an initial Refresh to load all templates and models.
func (*TemplateManager) Execute ¶
func (tm *TemplateManager) Execute(w io.Writer, name string, data interface{}) error
Execute renders a specific template by name, writing the output to the provided io.Writer. The `data` argument is passed to the template and can be used to provide context or dynamic values.
func (*TemplateManager) ExecuteTemplateString ¶ added in v1.0.0
func (tm *TemplateManager) ExecuteTemplateString(w io.Writer, content string, data interface{}) error
ExecuteTemplateString parses and executes a raw template string using the manager's function map. This is ideal for testing or previewing templates without saving them to disk.
func (*TemplateManager) GetConfig ¶ added in v1.0.0
func (tm *TemplateManager) GetConfig() TemplateConfig
GetConfig returns a copy of the current configuration. This mainly exists for concurrency-safety reasons.
func (*TemplateManager) GetRandomTemplate ¶
func (tm *TemplateManager) GetRandomTemplate() string
GetRandomTemplate returns the name of a randomly selected template from the set of loaded full templates. This is the primary mechanism for serving varied and unpredictable pages to web scrapers.
func (*TemplateManager) GetTemplateDir ¶ added in v1.0.0
func (tm *TemplateManager) GetTemplateDir() string
GetTemplateDir returns the template dir that the TemplateManager uses. This mainly exists for concurrency-safety reasons as well.
func (*TemplateManager) GetTemplateNames ¶ added in v1.0.0
func (tm *TemplateManager) GetTemplateNames() []string
GetTemplateNames returns a slice of the loaded template names. This mainly exists for concurrency-safety reasons, and because it returns the names of partial templates as well.
func (*TemplateManager) Refresh ¶
func (tm *TemplateManager) Refresh() error
Refresh reloads all templates from the filesystem and, if enabled, refreshes the list of available Markov models from the database. This function allows for updates to templates and models without restarting the application.
func (*TemplateManager) SetConfig ¶
func (tm *TemplateManager) SetConfig(config *TemplateConfig)
SetConfig applies a new configuration to the TemplateManager. This allows for changes to the engine's behavior, such as updating safety limits or the path whitelist, without needing to restart the application.