shared

package
v0.5.5-alpha Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2025 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LIVE_MODE        string = "live"
	DEBUG_MODE       string = "debug"
	DEVELOPMENT_MODE string = "development"
)
View Source
const FormData contextKey = "formData"
View Source
const JwtKey contextKey = "jwtToken"
View Source
const Request contextKey = "request"
View Source
const RequestBody contextKey = "requestBody"
View Source
const ResponseWriter contextKey = "ResponseWriter"

Variables

View Source
var (
	Write      bool
	Outputpath string = "../../cmd/hyperbricks-docs/hyperbricks-examples/"
)
View Source
var FuncMap = template.FuncMap{
	"random": Random,
	"valueOrEmpty": func(value interface{}) string {
		if value == nil {
			return ""
		}
		return fmt.Sprintf("%v", value)
	},
}

Create a FuncMap with a custom function

View Source
var Location string
View Source
var (
	Module string
)

Functions

func ApplyTemplate

func ApplyTemplate(templateStr string, data map[string]interface{}) (string, []error)

applyTemplate generates output based on the provided template and API data.

func CloneMap

func CloneMap(source map[string]interface{}) map[string]interface{}

cloneMap is a helper to do a shallow clone of map[string]interface{}

func DecodeWithBasicHooks

func DecodeWithBasicHooks(instance interface{}, config interface{}) []error

func EncloseContent

func EncloseContent(enclose string, content string) string

EncloseContent encloses the given content with the specified enclose string. The enclose string can be a single tag or a pair separated by '|'.

func ExtractHxData

func ExtractHxData(r *http.Request) (map[string]interface{}, error)

ExtractHxData extracts headers, form data, JSON payloads, and query parameters from an HTTP request.

func GenerateHash

func GenerateHash() string

func GenerateShortHash

func GenerateShortHash(input string, bits int) string

GenerateShortHash returns a short base62-encoded hash of the input string. 'bits' specifies how many bits of the SHA-256 digest to use. Default 48 bits is a good balance. Note: Using fewer bits increases collision risk; using more bits produces a longer string.

func GenerateTimestampRandomHash

func GenerateTimestampRandomHash(length int) string

GenerateTimestampRandomHash combines the current timestamp and a secure random number, hashes the combination using SHA-1, and returns the first 'length' hex characters.

func GenericTemplate

func GenericTemplate() *template.Template

// Why use clone ? Prevents concurrent modification: Clone() creates a separate instance per goroutine, avoiding map modification issues. Better performance: Reusing a base template reduces overhead compared to creating a new one every time. Cleaner & safer: No need for sync.Mutex, and avoids unnecessary allocations.

func GetGenericFuncMap

func GetGenericFuncMap() template.FuncMap

Lazy load function map based on context

func GetLogger

func GetLogger() *zap.SugaredLogger

GetLogger returns the singleton SugaredLogger instance

func HyperScriptErrorHash

func HyperScriptErrorHash(s string) string

func Init_configuration

func Init_configuration()

func IsJSONContent

func IsJSONContent(contentType string) bool

IsJSONContent checks if the Content-Type is application/json.

func IsMultipartForm

func IsMultipartForm(contentType string) bool

IsMultipartForm checks if the Content-Type is multipart/form-data.

func JoinHeaderValues

func JoinHeaderValues(values []string) string

JoinHeaderValues concatenates multiple header values into a single string separated by commas.

func JoinTestCode

func JoinTestCode(hyperbricks string, propertyTest string) []string

Helper function to combine the main configuration string with a property-specific test case.

func Random

func Random(args ...interface{}) interface{}

func RenderAllowedAttributes

func RenderAllowedAttributes(attributes map[string]interface{}, allowed []string) string

RenderAllowedAttributes filters and formats the allowed attributes for rendering in a consistent order.

func RenderValidationWarnings

func RenderValidationWarnings(warnings []string) string

func RenderValidationWarningsWithPath

func RenderValidationWarningsWithPath(warnings []string, hyperbrickspath []string) string

func RenderWarning

func RenderWarning(warning string) string

func SortedUniqueKeys

func SortedUniqueKeys(m map[string]interface{}) []string

SortedKeys returns the keys of the map sorted numerically or lexicographically. It caches the sorted keys for maps with the same set of keys. This uses TreeMap, is 5 times faster and uses 53 times less memory than the non-TreeMap

func StructToMap

func StructToMap(data interface{}) map[string]interface{}

Helper function to convert a struct to a map for easy validation in test cases.

func StructToMapRecursive

func StructToMapRecursive(input interface{}) map[string]interface{}

func ToMap

func ToMap(value interface{}) (map[string]interface{}, bool)

func TrimWrap

func TrimWrap(content, html string) string

TrimWrap removes the enclosing content around the placeholder '|'.

func Validate

func Validate(config interface{}) []error

func WriteToFile

func WriteToFile(filename, content string) error

Helper function to write test outputs to a file for documentation purposes.

Types

type CacheTime

type CacheTime struct {
	Duration time.Duration
}

CacheTime manages cache duration.

func (*CacheTime) Parse

func (ct *CacheTime) Parse(value string) error

Parse converts string to CacheTime.

func (CacheTime) String

func (ct CacheTime) String() string

String returns CacheTime as string.

func (*CacheTime) UnmarshalText

func (ct *CacheTime) UnmarshalText(text []byte) error

UnmarshalText allows mapstructure to decode CacheTime.

type Component

type Component = ComponentRendererConfig

type ComponentError

type ComponentError struct {
	Hash     string // non-collision hash
	File     string // Hyperbricks file
	Err      string // A descriptive error message
	Key      string // Current key of the component where the error occured
	Path     string // Path of the component in the hierarchy
	Rejected bool   // Rendering is rejected
	Type     string // Which HyperBricks type?
	Level    string // INFO, WARNING, otherwise ERROR
}

ComponentError represents an error associated with a component.

func HyperbricksDecodeError

func HyperbricksDecodeError(err string, path string, key string) (string, []ComponentError)

returns a anchor with error

func (ComponentError) Error

func (e ComponentError) Error() string

Error implements the error interface for ComponentError.

type ComponentRenderer

type ComponentRenderer interface {
	Renderer
}

type ComponentRendererConfig

type ComponentRendererConfig struct {
	Meta            `mapstructure:",squash"` // Embedding RendererConfig
	ExtraAttributes map[string]interface{}   `mapstructure:"attributes" description:"Extra attributes like id, data-role, data-action"`
	Enclose         string                   `mapstructure:"enclose" description:"The enclosing HTML element for the header divided by |"`
}

Basic config for ComponentRenderers

func (ComponentRendererConfig) GetConfigType

func (c ComponentRendererConfig) GetConfigType() string

func (ComponentRendererConfig) GetKey

func (c ComponentRendererConfig) GetKey() string

func (ComponentRendererConfig) GetPath

func (c ComponentRendererConfig) GetPath() string

type Composite

type Composite = CompositeRendererConfig

type CompositeError

type CompositeError struct {
	Err      string // A descriptive error message
	Key      string // Key of the component
	Path     string // Path of the component in the hierarchy
	Rejected bool   // Rendering is rejected
	Type     string // Which HyperBricks type?
	Level    string // INFO, WARNING, otherwise ERROR
}

ComponentError represents an error associated with a component.

func (CompositeError) Error

func (e CompositeError) Error() string

Error implements the error interface for ComponentError.

type CompositeRenderer

type CompositeRenderer interface {
	Renderer
}

CompositeRenderer extends Renderer to handle composite rendering (itself and children).

type CompositeRendererConfig

type CompositeRendererConfig struct {
	Meta  `mapstructure:",squash"`
	Items map[string]interface{} `mapstructure:",remain"`
}

type Config

type Config struct {
	Mode        string            `mapstructure:"mode"`
	Logger      LoggerConfig      `mapstructure:"logger"`
	Server      ServerConfig      `mapstructure:"server"`
	RateLimit   RateLimitConfig   `mapstructure:"rate_limit"`
	Development DevelopmentConfig `mapstructure:"development"`
	Debug       DebugConfig       `mapstructure:"debug"`
	Live        LiveConfig        `mapstructure:"live"`
	Directories map[string]string `mapstructure:"directories"`
	Plugins     PluginsConfig     `mapstructure:"plugins"`
	System      SystemConfig      `mapstructure:"system"`
}

Config structure with default values.

func GetHyperBricksConfiguration

func GetHyperBricksConfiguration() *Config

GetHyperBricksConfiguration returns the singleton instance of the Config.

type DebugConfig

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

type DevelopmentConfig

type DevelopmentConfig struct {
	Dashboard      bool `mapstructure:"dashboard"`
	FrontendErrors bool `mapstructure:"frontend_errors"`
	Watch          bool `mapstructure:"watch"`
	Reload         bool `mapstructure:"reload"`
}

type ExtendedRendererConfig

type ExtendedRendererConfig struct {
	Meta  // Embedding RendererConfig
	Value string
}

Example Extended struct

type LiveConfig

type LiveConfig struct {
	CacheTime CacheTime `mapstructure:"cache"`
}

type LoggerConfig

type LoggerConfig struct {
	Level string `mapstructure:"level"`
	Path  string `mapstructure:"path"`
}

LoggerConfig with defaults.

type Meta

type Meta struct {
	ConfigType      string `mapstructure:"@type" exclude:"true" description:"Identification for renderer"`
	ConfigCategory  string
	HyperBricksKey  string `mapstructure:"hyperbrickskey" exclude:"true"`
	HyperBricksPath string `mapstructure:"hyperbrickspath" exclude:"true"`
	HyperBricksFile string `mapstructure:"hyperbricksfile" exclude:"true"`
}

GENERIC CONFIG FIELDS

type PathKeyer

type PathKeyer interface {
	GetPath() string
	GetKey() string
	GetConfigType() string
}

type PluginConfig

type PluginConfig map[string]interface{}

PluginConfig is a generic configuration map for plugins.

type PluginRenderer

type PluginRenderer interface {
	Render(data interface{}, ctx context.Context) (string, []error)
}

RenderPlugin defines the interface for dynamic plugins.

type PluginsConfig

type PluginsConfig struct {
	Enabled []string          `mapstructure:"enabled"`
	Config  map[string]string `mapstructure:"config"`
}

type RateLimitConfig

type RateLimitConfig struct {
	RequestsPerSecond int `mapstructure:"requests_per_second"`
	Burst             int `mapstructure:"burst"`
}

type RenderFunc

type RenderFunc func(contentType string, data interface{}) (string, []error)

RenderFunc defines the signature for the render callback.

type Renderer

type Renderer interface {
	Render(instance interface{}, ctx context.Context) (string, []error)
	Types() []string
}

type ServerConfig

type ServerConfig struct {
	Port         int           `mapstructure:"port"`
	Beautify     bool          `mapstructure:"beautify"`
	ReadTimeout  time.Duration `mapstructure:"read_timeout"`
	WriteTimeout time.Duration `mapstructure:"write_timeout"`
	IdleTimeout  time.Duration `mapstructure:"idle_timeout"`
}

ServerConfig with defaults.

type SystemConfig

type SystemConfig struct {
	MetricsWatchInterval time.Duration `mapstructure:"metrics_watch_interval"`
}

Jump to

Keyboard shortcuts

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