2024-03-13 02:27:15 +01:00
|
|
|
package templates
|
2021-08-28 00:15:28 +05:30
|
|
|
|
|
|
|
|
import (
|
2024-03-13 21:02:36 +01:00
|
|
|
"github.com/projectdiscovery/utils/conversion"
|
2024-03-10 22:29:55 +01:00
|
|
|
mapsutil "github.com/projectdiscovery/utils/maps"
|
2021-08-28 00:15:28 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Templates is a cache for caching and storing templates for reuse.
|
2024-03-13 02:27:15 +01:00
|
|
|
type Cache struct {
|
2024-03-13 21:02:36 +01:00
|
|
|
items *mapsutil.SyncLockMap[string, parsedTemplate]
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// New returns a new templates cache
|
2024-03-13 02:27:15 +01:00
|
|
|
func NewCache() *Cache {
|
2024-03-13 21:02:36 +01:00
|
|
|
return &Cache{items: mapsutil.NewSyncLockMap[string, parsedTemplate]()}
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
|
|
|
|
|
2024-03-13 21:02:36 +01:00
|
|
|
type parsedTemplate struct {
|
2024-03-13 02:27:15 +01:00
|
|
|
template *Template
|
2024-03-13 21:02:36 +01:00
|
|
|
raw string
|
2021-08-28 00:15:28 +05:30
|
|
|
err error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Has returns true if the cache has a template. The template
|
|
|
|
|
// is returned along with any errors if found.
|
2024-03-13 21:02:36 +01:00
|
|
|
func (t *Cache) Has(template string) (*Template, []byte, error) {
|
2024-03-10 22:29:55 +01:00
|
|
|
value, ok := t.items.Get(template)
|
2021-08-28 00:15:28 +05:30
|
|
|
if !ok {
|
2024-03-13 21:02:36 +01:00
|
|
|
return nil, nil, nil
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
2024-03-13 21:02:36 +01:00
|
|
|
return value.template, conversion.Bytes(value.raw), value.err
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Store stores a template with data and error
|
2024-03-13 21:02:36 +01:00
|
|
|
func (t *Cache) Store(id string, tpl *Template, raw []byte, err error) {
|
|
|
|
|
_ = t.items.Set(id, parsedTemplate{template: tpl, raw: conversion.String(raw), err: err})
|
2024-03-10 22:29:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Purge the cache
|
2024-03-13 02:27:15 +01:00
|
|
|
func (t *Cache) Purge() {
|
2024-03-10 22:29:55 +01:00
|
|
|
t.items.Clear()
|
2021-08-28 00:15:28 +05:30
|
|
|
}
|