Documentation
¶
Index ¶
- Constants
- Variables
- func ExtractResolverDeps(in ResolverDepsInput) []string
- func InitFromAppConfig(ctx context.Context, cfg GoTemplateConfigInput)
- func ResetAppConfigForTesting()
- func ResetDefaultCache()
- func SetAllowEnvFunctions(allow bool)
- func SetCacheFactory(factory func() *TemplateCache)
- func SetContextFuncBinderFactory(factory func(ctx context.Context) template.FuncMap)
- func SetDefaultCacheSize(size int)
- func SetExtensionFuncMapFactory(factory func() template.FuncMap)
- func ValidateSyntax(content, leftDelim, rightDelim string) error
- type DepScanContext
- type Example
- type ExecuteResult
- type ExtFunction
- type ExtFunctionList
- type GoTemplateConfigInput
- type GoTemplatingContent
- type MissingKeyOption
- type Replacement
- type ResolverDepsInput
- type Service
- type TemplateCache
- func (c *TemplateCache) Clear()
- func (c *TemplateCache) ClearWithStats()
- func (c *TemplateCache) Get(key string) (*template.Template, bool)
- func (c *TemplateCache) GetDetailedStats(topN int) TemplateCacheStats
- func (c *TemplateCache) Put(key string, tmpl *template.Template, templateName string)
- func (c *TemplateCache) ResetStats()
- func (c *TemplateCache) Stats() TemplateCacheStats
- type TemplateCacheStats
- type TemplateOptions
- type TemplateReference
- type TemplateStat
Examples ¶
Constants ¶
const ( // DefaultLeftDelim is the default left delimiter for templates DefaultLeftDelim = "{{" // DefaultRightDelim is the default right delimiter for templates DefaultRightDelim = "}}" )
const DepScanContextKey = "__scafctl_dep_scan_context"
DepScanContextKey is the reserved input-map key under which resolver dependency extraction context is passed to a template-based provider's ExtractDependencies function. A provider that resolves inline templates should read this key, falling back to best-effort local computation when it is absent.
Variables ¶
var ( // DefaultTemplateCacheSize is the default size for the package-level cache. DefaultTemplateCacheSize = settings.DefaultGoTemplateCacheSize )
Package-level default cache (mirrors the CEL cache pattern)
Functions ¶
func ExtractResolverDeps ¶ added in v0.33.0
func ExtractResolverDeps(in ResolverDepsInput) []string
ExtractResolverDeps returns the resolver dependency names referenced by root-level accessors in a Go template, applying context-aware disambiguation:
- {{ ._.name }} is always treated as a resolver dependency.
- {{ .field }} is treated as a resolver dependency only when there is no data input and the field is not a forEach alias. When a data input is present, a field matching a statically-known data key (or any field when the data key set is not statically known) is treated as local context.
- Special variables ({{ .__item }}, {{ .__self }}, ...) and scoped references (inside {{ with }}/{{ range }} bodies) are ignored.
The returned names are de-duplicated and preserve first-seen order. Template parse errors yield a nil slice (extraction is best-effort).
func InitFromAppConfig ¶ added in v0.6.0
func InitFromAppConfig(ctx context.Context, cfg GoTemplateConfigInput)
InitFromAppConfig initializes the Go template subsystem with application configuration. This should be called once during application startup, before any Go templates are evaluated.
This function:
- Creates a new template cache with the specified size
- Registers the cache as the default cache via SetCacheFactory
The function is idempotent - subsequent calls after the first are no-ops.
Example:
gotmpl.InitFromAppConfig(ctx, gotmpl.GoTemplateConfigInput{
CacheSize: 10000,
EnableMetrics: true,
})
func ResetAppConfigForTesting ¶ added in v0.6.0
func ResetAppConfigForTesting()
ResetAppConfigForTesting resets the app config state for testing purposes. This should only be called from tests.
func ResetDefaultCache ¶ added in v0.6.0
func ResetDefaultCache()
ResetDefaultCache clears and recreates the default cache. This is intended for testing only.
WARNING: This is not thread-safe with respect to ongoing template compilations. Only call this from test setup functions, not from production code.
func SetAllowEnvFunctions ¶ added in v0.6.0
func SetAllowEnvFunctions(allow bool)
SetAllowEnvFunctions controls whether the sprig 'env' and 'expandenv' Go template functions are available. Call this once after loading application config. Defaults to false (deny) — env functions are stripped unless explicitly enabled.
func SetCacheFactory ¶ added in v0.6.0
func SetCacheFactory(factory func() *TemplateCache)
SetCacheFactory sets the factory function used to get the global template cache. This should be called once during application initialization (e.g. from InitFromAppConfig). It allows the default cache to be configured from application config without circular dependencies.
This function is thread-safe and uses sync.Once to ensure it's only set once.
func SetContextFuncBinderFactory ¶ added in v0.6.0
SetContextFuncBinderFactory registers a factory that produces context-aware template.FuncMap entries. It is called once per template execution with the current context so that functions like `cel` can respect cancellation and timeouts. Call this during application initialization to avoid import cycles.
func SetDefaultCacheSize ¶ added in v0.6.0
func SetDefaultCacheSize(size int)
SetDefaultCacheSize sets the size of the default cache. This must be called before the first call to GetDefaultCache() or Service.Execute(). Once the cache is initialized, this function has no effect.
func SetExtensionFuncMapFactory ¶ added in v0.6.0
SetExtensionFuncMapFactory sets the factory function used to provide extension template functions (sprig + custom). This should be called once during application initialization to wire in extension functions without creating import cycles.
This function is thread-safe and uses sync.Once to ensure it's only set once.
Example (called during application initialization):
gotmpl.SetExtensionFuncMapFactory(ext.AllFuncMap)
func ValidateSyntax ¶ added in v0.6.0
ValidateSyntax checks a Go template for parse errors without executing it. It returns nil if the template is syntactically valid. Use leftDelim/rightDelim to override the default "{{" / "}}" delimiters (pass empty strings for defaults).
Types ¶
type DepScanContext ¶ added in v0.33.0
type DepScanContext struct {
// HasDataInput indicates the step supplies an explicit data input.
HasDataInput bool
// DataKeys is the set of top-level keys the data input provides. Only
// meaningful when DataKeysComplete is true.
DataKeys map[string]bool
// DataKeysComplete indicates DataKeys is an authoritative, complete key set.
DataKeysComplete bool
// Aliases is the set of forEach item/index alias names bound locally.
Aliases map[string]bool
}
DepScanContext carries the pre-computed template scan context (data-input key set and forEach aliases) from the dependency-graph builder into a provider's ExtractDependencies function. It exists because that function receives only the provider input map and cannot otherwise see sibling constructs such as a forEach clause or statically analyse CEL data expressions.
type Example ¶ added in v0.6.0
type Example struct {
// Description explains what the example demonstrates
Description string `` /* 138-byte string literal not displayed */
// Template is the Go template snippet showing usage
Template string `` /* 138-byte string literal not displayed */
// Links contains reference URLs for the example
Links []string `json:"links,omitempty" yaml:"links,omitempty" doc:"Reference URLs for the example" maxItems:"10"`
}
Example describes a usage example for a Go template function.
type ExecuteResult ¶
type ExecuteResult struct {
// Output is the rendered template content
Output string `json:"output" yaml:"output" doc:"Rendered template content" maxLength:"10485760"`
// TemplateName is the name/identifier of the template
TemplateName string `json:"templateName" yaml:"templateName" doc:"Name/identifier of the template" maxLength:"512" example:"greeting.tmpl"`
// ReplacementsMade is the number of replacements that were applied
ReplacementsMade int `json:"replacementsMade" yaml:"replacementsMade" doc:"Number of replacements that were applied" maximum:"1000" example:"3"`
}
ExecuteResult contains the result of template execution
func Execute ¶
func Execute(ctx context.Context, opts TemplateOptions) (*ExecuteResult, error)
Execute is a convenience function that creates a service and executes a template For one-off template execution without custom default functions
Example ¶
ExampleExecute demonstrates basic template execution
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
result, err := gotmpl.Execute(ctx, gotmpl.TemplateOptions{
Name: "greeting.tmpl",
Content: "Hello, {{.Name}}! You are {{.Age}} years old.",
Data: map[string]any{
"Name": "Alice",
"Age": 30,
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Hello, Alice! You are 30 years old.
type ExtFunction ¶ added in v0.6.0
type ExtFunction struct {
// Name is the function name as used in templates (e.g., "toHcl", "upper")
Name string `json:"name,omitempty" yaml:"name,omitempty" doc:"Function name as used in templates" maxLength:"128" example:"toHcl"`
// Description is a human-readable description of the function
Description string `` /* 164-byte string literal not displayed */
// Links contains reference URLs (documentation, source code, etc.)
Links []string `json:"links,omitempty" yaml:"links,omitempty" doc:"Reference URLs for documentation" maxItems:"10"`
// Examples provides usage examples for documentation and discoverability
Examples []Example `json:"examples,omitempty" yaml:"examples,omitempty" doc:"Usage examples for documentation" maxItems:"20"`
// Custom indicates whether this is a scafctl-specific function (true)
// or a third-party/built-in function (false, e.g., sprig functions)
Custom bool `json:"custom,omitempty" yaml:"custom,omitempty" doc:"Whether this is a scafctl-specific function"`
// Func is the template.FuncMap entry for this function.
// Excluded from JSON/YAML serialization.
Func template.FuncMap `json:"-" yaml:"-" doc:"Template FuncMap entry for this function"`
}
ExtFunction describes a Go template function extension with metadata for discoverability via MCP tools and CLI commands.
func (ExtFunction) GetDescription ¶ added in v0.9.0
func (f ExtFunction) GetDescription() string
GetDescription returns the function description for search filtering.
func (ExtFunction) GetName ¶ added in v0.6.0
func (f ExtFunction) GetName() string
GetName returns the function name, implementing the named interface for use with generic filter helpers.
type ExtFunctionList ¶ added in v0.6.0
type ExtFunctionList []ExtFunction
ExtFunctionList is a list of ExtFunction entries.
func (ExtFunctionList) FuncMap ¶ added in v0.6.0
func (l ExtFunctionList) FuncMap() template.FuncMap
FuncMap merges all individual Func entries into a single template.FuncMap. Later entries override earlier ones if they share the same function name.
type GoTemplateConfigInput ¶ added in v0.6.0
type GoTemplateConfigInput struct {
// CacheSize is the maximum number of compiled templates to cache
CacheSize int `json:"cacheSize" yaml:"cacheSize" doc:"Maximum number of compiled templates to cache" maximum:"100000" example:"10000"`
// EnableMetrics enables template cache metrics collection
EnableMetrics bool `json:"enableMetrics" yaml:"enableMetrics" doc:"Enable template cache metrics collection"`
// AllowEnvFunctions enables the sprig env/expandenv functions.
// When false (default), these functions are stripped from the template func map
// to prevent accidental or malicious env-var exfiltration.
AllowEnvFunctions bool `json:"allowEnvFunctions" yaml:"allowEnvFunctions" doc:"Allow sprig env/expandenv functions (default: false)"`
}
GoTemplateConfigInput holds the configuration values for Go template initialization. This mirrors config.GoTemplateConfig but avoids circular dependencies.
type GoTemplatingContent ¶
type GoTemplatingContent string
type MissingKeyOption ¶
type MissingKeyOption string
MissingKeyOption defines the behavior when a map key is missing during template execution
const ( // MissingKeyDefault continues execution and prints "<no value>" for missing keys. // Named after Go's missingkey=default template option. MissingKeyDefault MissingKeyOption = "default" // MissingKeyZero returns the zero value for the map type's element MissingKeyZero MissingKeyOption = "zero" // MissingKeyError stops execution immediately with an error MissingKeyError MissingKeyOption = "error" )
type Replacement ¶
type Replacement struct {
// Find is the string to search for in the template content
Find string `json:"find" yaml:"find" doc:"String to search for in the template content" maxLength:"4096" example:"${LITERAL}"`
// Replace is the temporary replacement value
// If empty, a UUID will be generated automatically
Replace string `` /* 131-byte string literal not displayed */
// RestoreAs is the value written back into the output after execution.
// If empty, Find is restored verbatim (the default). Set this to restore a
// different value than what was matched -- e.g. to strip fence markers while
// preserving only the inner content of a protected block.
RestoreAs string `` /* 163-byte string literal not displayed */
}
Replacement defines a string replacement to perform before/after templating
type ResolverDepsInput ¶ added in v0.33.0
type ResolverDepsInput struct {
// Template is the raw Go template text to scan. Callers should strip any
// ignored/raw pass-through regions before passing the text.
Template string
// LeftDelim and RightDelim are the template delimiters. Empty values fall
// back to the standard "{{" and "}}".
LeftDelim string
RightDelim string
// HasDataInput indicates the step supplies an explicit `data` input. When
// true, the template's root namespace is dominated by the data context, so
// bare {{ .field }} accessors are resolved against the data rather than the
// resolver graph.
HasDataInput bool
// DataKeys is the set of top-level keys the `data` input provides. It is
// only meaningful when DataKeysComplete is true.
DataKeys map[string]bool
// DataKeysComplete indicates DataKeys is an authoritative, complete list of
// the keys the data input provides. It is false when the data input is
// dynamic (e.g. a rslvr reference or a non-map-literal expression) and the
// key set cannot be determined statically.
DataKeysComplete bool
// Aliases is the set of forEach item/index alias names bound locally for the
// step. They are never resolver dependencies.
Aliases map[string]bool
}
ResolverDepsInput configures resolver-dependency extraction from a Go template string. It captures everything the extractor needs to correctly disambiguate a {{ .field }} accessor between a resolver reference and a local template-context binding (a data-input key or a forEach loop alias).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides template execution capabilities
func NewService ¶
NewService creates a new template service with all registered extension functions (sprig + custom scafctl extensions) available by default. If additionalFuncs is provided, those functions are merged on top of the extensions, allowing callers to override any extension function.
Extension functions are provided via SetExtensionFuncMapFactory, which should be called during application initialization.
Use NewServiceRaw to create a service without auto-registered extensions.
func NewServiceRaw ¶ added in v0.6.0
NewServiceRaw creates a new template service without any auto-registered extension functions. Only the explicitly provided functions will be available. Use this when you want a bare template service without sprig or custom extensions.
func NewServiceWithCache ¶ added in v0.6.0
func NewServiceWithCache(additionalFuncs template.FuncMap, cache *TemplateCache) *Service
NewServiceWithCache creates a new template service with a custom cache. This is useful for testing or when you want isolated cache instances.
func (*Service) Execute ¶
func (s *Service) Execute(ctx context.Context, opts TemplateOptions) (*ExecuteResult, error)
Execute renders a template with the provided options
Example (Complex) ¶
ExampleService_Execute_complex demonstrates combining multiple features
package main
import (
"context"
"fmt"
"log"
"text/template"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
// Create service with helper functions
svc := gotmpl.NewService(template.FuncMap{
"default": func(defaultVal, val string) string {
if val == "" {
return defaultVal
}
return val
},
})
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "report.tmpl",
Content: "User: [[.Name]], Status: [[default \"inactive\" .Status]], Code: LITERAL_CODE",
LeftDelim: "[[",
RightDelim: "]]",
Data: map[string]any{
"Name": "David",
"Status": "",
},
Replacements: []gotmpl.Replacement{
{Find: "LITERAL_CODE", Replace: "TEMP_12345"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: User: David, Status: inactive, Code: LITERAL_CODE
Example (CustomDelimiters) ¶
ExampleService_Execute_customDelimiters shows using custom delimiters
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "jinja-style.tmpl",
Content: "Welcome, [[.User]]!",
LeftDelim: "[[",
RightDelim: "]]",
Data: map[string]any{
"User": "Bob",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Welcome, Bob!
Example (CustomFunctions) ¶
ExampleService_Execute_customFunctions demonstrates using custom template functions
package main
import (
"context"
"fmt"
"log"
"strings"
"text/template"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
// Create service with default functions
svc := gotmpl.NewService(template.FuncMap{
"upper": strings.ToUpper,
"lower": strings.ToLower,
})
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "formatted.tmpl",
Content: "{{upper .FirstName}} {{lower .LastName}}",
Data: map[string]any{
"FirstName": "john",
"LastName": "DOE",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: JOHN doe
Example (LoopAndConditionals) ¶
ExampleService_Execute_loopAndConditionals shows template control structures
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
content := `{{if .Title}}Title: {{.Title}}
{{end}}Items:{{range .Items}}
- {{.}}{{end}}`
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "list.tmpl",
Content: content,
Data: map[string]any{
"Title": "Shopping List",
"Items": []string{"Apples", "Bananas", "Oranges"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Title: Shopping List Items: - Apples - Bananas - Oranges
Example (MissingKeyHandling) ¶
ExampleService_Execute_missingKeyHandling demonstrates handling missing keys
package main
import (
"context"
"fmt"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
// Default behavior: prints "<no value>"
result1, _ := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "default.tmpl",
Content: "Status: {{.Status}}",
Data: map[string]any{}, // Status key missing
MissingKey: gotmpl.MissingKeyDefault,
})
fmt.Println(result1.Output)
// Zero behavior: returns zero value (empty string for string type)
result2, _ := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "zero.tmpl",
Content: "Count: {{.Count}}",
Data: map[string]any{}, // Count key missing
MissingKey: gotmpl.MissingKeyZero,
})
fmt.Println(result2.Output)
}
Output: Status: <no value> Count: <no value>
Example (Replacements) ¶
ExampleService_Execute_replacements shows protecting literal strings from template processing
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
// Template contains both template syntax and literal template syntax
content := `Name: {{.Name}}
Literal template syntax: {{KEEP_THIS_LITERAL}}`
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "mixed.tmpl",
Content: content,
Data: map[string]any{
"Name": "Charlie",
},
Replacements: []gotmpl.Replacement{
{Find: "{{KEEP_THIS_LITERAL}}"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Name: Charlie Literal template syntax: {{KEEP_THIS_LITERAL}}
func (*Service) GetReferences ¶
func (s *Service) GetReferences(ctx context.Context, opts TemplateOptions) ([]TemplateReference, error)
GetReferences extracts all references to Data from a Go template This method parses the template and extracts variable references (e.g., .User, .Items) It excludes function calls and Go template control variables (like $var)
Example ¶
ExampleService_GetReferences demonstrates extracting references using the Service
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
refs, err := svc.GetReferences(ctx, gotmpl.TemplateOptions{
Name: "config.tmpl",
Content: "[[.App.Name]] version [[.App.Version]]",
LeftDelim: "[[",
RightDelim: "]]",
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Template references:")
for _, ref := range refs {
fmt.Printf(" %s\n", ref.Path)
}
}
Output: Template references: .App.Name .App.Version
type TemplateCache ¶ added in v0.6.0
type TemplateCache struct {
// contains filtered or unexported fields
}
TemplateCache is a thread-safe LRU cache for compiled Go templates. It caches parsed *template.Template objects by a hash of the template content and configuration, allowing reuse of expensive parse operations.
The cache also tracks detailed template-level metrics for monitoring and debugging purposes.
func GetAppConfigCache ¶ added in v0.6.0
func GetAppConfigCache() *TemplateCache
GetAppConfigCache returns the cache created by InitFromAppConfig. Returns nil if InitFromAppConfig has not been called.
func GetDefaultCache ¶ added in v0.6.0
func GetDefaultCache() *TemplateCache
GetDefaultCache returns the package-level cache instance. If a cache factory has been registered via SetCacheFactory, that factory is used. Otherwise, the cache is lazily initialized on first access with DefaultTemplateCacheSize entries. All calls return the same cache instance (singleton pattern).
Use this when you need to access cache statistics:
stats := gotmpl.GetDefaultCache().Stats()
fmt.Printf("Cache hit rate: %.1f%%\n", stats.HitRate)
func NewTemplateCache ¶ added in v0.6.0
func NewTemplateCache(maxSize int) *TemplateCache
NewTemplateCache creates a new template cache with the specified maximum size. When the cache reaches maxSize, the least recently used entry will be evicted. A maxSize of 0 or negative value defaults to 100.
Template-level metrics are tracked for the top 1000 most accessed templates to avoid unbounded memory growth.
func (*TemplateCache) Clear ¶ added in v0.6.0
func (c *TemplateCache) Clear()
Clear removes all entries from the cache but preserves statistics. Use ClearWithStats() to also reset hit/miss counters.
func (*TemplateCache) ClearWithStats ¶ added in v0.6.0
func (c *TemplateCache) ClearWithStats()
ClearWithStats removes all entries and resets all statistics to zero.
func (*TemplateCache) Get ¶ added in v0.6.0
func (c *TemplateCache) Get(key string) (*template.Template, bool)
Get retrieves a template from the cache if it exists. Returns a clone of the cached template and true if found, nil and false otherwise. The clone is safe for concurrent execution with different data.
func (*TemplateCache) GetDetailedStats ¶ added in v0.6.0
func (c *TemplateCache) GetDetailedStats(topN int) TemplateCacheStats
GetDetailedStats returns cache statistics including template-level metrics. If topN is 0, returns all tracked templates. Otherwise returns the top N most accessed templates sorted by hit count (descending).
func (*TemplateCache) Put ¶ added in v0.6.0
func (c *TemplateCache) Put(key string, tmpl *template.Template, templateName string)
Put adds a template to the cache with its name for metrics tracking. If the cache is full, it evicts the least recently used entry before adding the new one.
func (*TemplateCache) ResetStats ¶ added in v0.6.0
func (c *TemplateCache) ResetStats()
ResetStats resets cache statistics (hits, misses, evictions) without removing cached entries.
func (*TemplateCache) Stats ¶ added in v0.6.0
func (c *TemplateCache) Stats() TemplateCacheStats
Stats returns cache statistics.
type TemplateCacheStats ¶ added in v0.6.0
type TemplateCacheStats struct {
Size int `json:"size" yaml:"size" doc:"Current number of cached templates" maximum:"100000" example:"42"`
MaxSize int `json:"max_size" yaml:"max_size" doc:"Maximum cache capacity" maximum:"100000" example:"1000"`
Hits uint64 `json:"hits" yaml:"hits" doc:"Total cache hits"`
Misses uint64 `json:"misses" yaml:"misses" doc:"Total cache misses"`
Evictions uint64 `json:"evictions" yaml:"evictions" doc:"Total cache evictions"`
HitRate float64 `json:"hit_rate" yaml:"hit_rate" doc:"Cache hit rate percentage"`
TotalAccesses uint64 `json:"total_accesses" yaml:"total_accesses" doc:"Total number of cache accesses"`
TopTemplates []TemplateStat `json:"top_templates,omitempty" yaml:"top_templates,omitempty" doc:"Most frequently accessed templates" maxItems:"50"`
}
TemplateCacheStats contains cache performance statistics.
type TemplateOptions ¶
type TemplateOptions struct {
// Content is the template content as a string
Content string `json:"content" yaml:"content" doc:"Template content as a string" maxLength:"1048576" example:"Hello {{ .Name }}"`
// Name is the reference name/identifier for the template (e.g., file path)
// Used in logging and error messages
Name string `json:"name" yaml:"name" doc:"Reference name/identifier for the template" maxLength:"512" example:"greeting.tmpl"`
// Data is the data source passed to the template during execution
Data any `json:"data,omitempty" yaml:"data,omitempty" doc:"Data source passed to the template during execution"`
// LeftDelim sets the left action delimiter (default: "{{")
LeftDelim string `json:"leftDelim,omitempty" yaml:"leftDelim,omitempty" doc:"Left action delimiter" maxLength:"8" example:"{{"`
// RightDelim sets the right action delimiter (default: "}}")
RightDelim string `json:"rightDelim,omitempty" yaml:"rightDelim,omitempty" doc:"Right action delimiter" maxLength:"8" example:"}}"`
// Replacements is a map of strings to replace before template execution
// The key is replaced with a UUID placeholder, then restored after execution
// This helps avoid template parsing errors for content that should be literal
Replacements []Replacement `` /* 143-byte string literal not displayed */
// Funcs is a map of custom template functions to make available
// These are added to the template's function map
Funcs template.FuncMap `json:"-" yaml:"-" doc:"Custom template functions to make available"`
// MissingKey controls the behavior when a map key is missing
// Default: MissingKeyError (stops execution with an error)
// Options: MissingKeyDefault, MissingKeyZero, MissingKeyError
MissingKey MissingKeyOption `` /* 144-byte string literal not displayed */
// DisableBuiltinFuncs disables the built-in template functions
// By default, basic functions like "html", "js", etc. are available
DisableBuiltinFuncs bool `json:"disableBuiltinFuncs,omitempty" yaml:"disableBuiltinFuncs,omitempty" doc:"Disables the built-in template functions"`
}
TemplateOptions contains configuration for template execution
type TemplateReference ¶
type TemplateReference struct {
// Path is the dot-notation path to the data (e.g., ".User.Name", ".Items")
Path string
// Position is the line:column position in the template (if available)
Position string
// Scoped indicates the reference is inside a {{ with }} or {{ range }} body
// where dot has been rebound. Scoped references refer to fields of the
// narrowed context, not the root data.
//
// Deduplication: if the same path appears both scoped and unscoped, the
// entry is marked Scoped=false (unscoped wins) so that dependency
// extractors do not miss a real top-level reference.
Scoped bool
}
TemplateReference represents a reference to data in a template
func GetGoTemplateReferences ¶
func GetGoTemplateReferences(templateContent, leftDelim, rightDelim string) ([]TemplateReference, error)
GetGoTemplateReferences is a convenience function that creates a service and extracts references For one-off reference extraction without needing to create a service
Example ¶
ExampleGetGoTemplateReferences demonstrates extracting data references from templates using the convenience function
package main
import (
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
)
func main() {
template := `
{{if .User.IsAdmin}}
Welcome, {{.User.Name}}!
{{range .User.Permissions}}
- {{.}}
{{end}}
{{end}}
`
refs, err := gotmpl.GetGoTemplateReferences(template, "", "")
if err != nil {
log.Fatal(err)
}
fmt.Println("Found references:")
for _, ref := range refs {
fmt.Printf(" %s\n", ref.Path)
}
}
Output: Found references: .User.IsAdmin .User.Name .User.Permissions
type TemplateStat ¶ added in v0.6.0
type TemplateStat struct {
TemplateName string `json:"template_name" yaml:"template_name" doc:"Template name/identifier" maxLength:"512" example:"greeting.tmpl"`
Hits uint64 `json:"hits" yaml:"hits" doc:"Number of cache hits for this template"`
LastAccess time.Time `json:"last_access" yaml:"last_access" doc:"Time of last access"`
}
TemplateStat contains statistics for a specific template.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package detail provides functions for building structured output representations of Go template extension functions.
|
Package detail provides functions for building structured output representations of Go template extension functions. |
|
Package ext provides the Go template extension function registry.
|
Package ext provides the Go template extension function registry. |
|
celeval
Package celeval provides a Go template extension function for evaluating CEL (Common Expression Language) expressions inline within Go templates.
|
Package celeval provides a Go template extension function for evaluating CEL (Common Expression Language) expressions inline within Go templates. |
|
collections
Package collections provides Go template extension functions for filtering and projecting lists of maps, enabling common data transformation patterns directly within Go templates.
|
Package collections provides Go template extension functions for filtering and projecting lists of maps, enabling common data transformation patterns directly within Go templates. |
|
dns
Package dns provides Go template extension functions for converting arbitrary strings into DNS-safe label format (RFC 1123).
|
Package dns provides Go template extension functions for converting arbitrary strings into DNS-safe label format (RFC 1123). |
|
hcl
Package hcl provides a Go template extension function for converting Go objects into HCL (HashiCorp Configuration Language) format.
|
Package hcl provides a Go template extension function for converting Go objects into HCL (HashiCorp Configuration Language) format. |
|
host
Package host provides Go template extension functions that expose the host's resolved XDG configuration directory.
|
Package host provides Go template extension functions that expose the host's resolved XDG configuration directory. |
|
yaml
Package yaml provides Go template extension functions for YAML serialization and deserialization.
|
Package yaml provides Go template extension functions for YAML serialization and deserialization. |