Documentation
¶
Overview ¶
Package hocon is a pure-Go (no cgo, stdlib-only) parser for HOCON, the Human-Optimized Config Object Notation used by Typesafe Config. HOCON is a superset of JSON that adds unquoted keys and strings (which may contain internal whitespace, e.g. `a b c : 42`), `=` as an alias for `:`, optional commas and root braces, `#` and `//` comments, dotted-path keys, deep object merging of duplicate keys, array and value concatenation, `${path}` / `${?path}` substitutions with environment fallback, `+=` self-append, `include` directives (`"file"`, `file(...)`, `url(...)`, `classpath(...)` and `required(...)`) and duration / size unit suffixes. Whitespace between the simple values of a concatenation is preserved verbatim, and the spec's "forbidden characters" (plus, dollar, quote, braces, brackets, colon, equals, comma, hash, backtick, caret, question, bang, at, star, ampersand, backslash, and the two-character comment opener //) may neither appear in an unquoted string nor begin a value or key.
The entry point is Parse, which lexes, parses, merges and resolves an input string into a *Config. Substitutions are resolved after the whole tree is built. Includes and environment lookups are performed through injectable seams (WithIncludeResolver, WithEnv) so callers — and tests — need never touch the filesystem or process environment. A plain include silently skips a resource that cannot be resolved (the resolver reports ErrIncludeNotFound or an fs.ErrNotExist-wrapped error); wrapping the target in `required(...)` turns a missing resource into a parse error. classpath resolution has no meaning outside a JVM, so it is delegated entirely to the resolver seam.
Values are modelled by ConfigValue and classified by ConfigValueType. Typed accessors on Config (GetString, GetInt, GetFloat, GetBool, GetDuration, GetBytes, GetList, GetObject, GetOrElse, HasPath) read dotted paths and report typed errors. Because a `.` in a dotted path always starts a new object level, a key that contains a literal dot (written quoted, e.g. `"a.b" = 1`) is addressed with the segmented accessors Config.GetValuePath and Config.HasPathSegments, which take explicit path segments. Config.Render serialises a config back to HOCON or JSON.
Index ¶
- Variables
- type Config
- func (c *Config) GetBool(path string) (bool, error)
- func (c *Config) GetBytes(path string) (int64, error)
- func (c *Config) GetDuration(path string) (time.Duration, error)
- func (c *Config) GetFloat(path string) (float64, error)
- func (c *Config) GetInt(path string) (int64, error)
- func (c *Config) GetList(path string) ([]*ConfigValue, error)
- func (c *Config) GetObject(path string) (*Config, error)
- func (c *Config) GetOrElse(path string, def *ConfigValue) *ConfigValue
- func (c *Config) GetString(path string) (string, error)
- func (c *Config) GetValue(path string) (*ConfigValue, error)
- func (c *Config) GetValuePath(segments ...string) (*ConfigValue, error)
- func (c *Config) HasPath(path string) bool
- func (c *Config) HasPathSegments(segments ...string) bool
- func (c *Config) Render(opts RenderOptions) string
- func (c *Config) Root() *ConfigValue
- func (c *Config) WithFallback(fallback *Config) *Config
- type ConfigValue
- type ConfigValueType
- type EnvLookup
- type IncludeResolver
- type Option
- type ParseError
- type PathError
- type RenderOptions
- type ResolveError
Constants ¶
This section is empty.
Variables ¶
var ErrIncludeNotFound = errors.New("include resource not found")
ErrIncludeNotFound may be returned by an IncludeResolver to signal that the requested resource does not exist. A plain `include` treats a not-found resource as an empty object (silently skipped); an `include required(...)` turns it into a parse error. Resolvers built on the filesystem can also just return an fs.ErrNotExist-wrapped error, which is recognised identically.
var ErrMissing = errors.New("path not found")
ErrMissing is returned (wrapped in a *PathError) when a path is absent.
var ErrWrongType = errors.New("wrong value type")
ErrWrongType is returned (wrapped in a *PathError) when a value at a path exists but is not of the requested type.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config is a resolved HOCON document: a tree rooted at an object.
func (*Config) GetBytes ¶
GetBytes returns a size in bytes at path. A bare number is a byte count; a string may carry a unit suffix (`10MB`, `1GiB`, `512 bytes`, ...).
func (*Config) GetDuration ¶
GetDuration returns the duration at path. A bare number is milliseconds; a string may carry a unit suffix (`10s`, `5 min`, `100ms`, ...).
func (*Config) GetList ¶
func (c *Config) GetList(path string) ([]*ConfigValue, error)
GetList returns the array elements at path.
func (*Config) GetOrElse ¶
func (c *Config) GetOrElse(path string, def *ConfigValue) *ConfigValue
GetOrElse returns the value at path, or def when the path is absent.
func (*Config) GetValue ¶
func (c *Config) GetValue(path string) (*ConfigValue, error)
GetValue returns the ConfigValue at a dotted path. Each `.` in path starts a new object level, so `GetValue("a.b")` descends into object `a` then key `b`. A key that itself contains a literal dot — written quoted in HOCON, e.g. `"a.b" = 1` — cannot be reached this way; use Config.GetValuePath with the key as a single explicit segment (`GetValuePath("a.b")`).
func (*Config) GetValuePath ¶
func (c *Config) GetValuePath(segments ...string) (*ConfigValue, error)
GetValuePath returns the ConfigValue at a path given as explicit segments, bypassing dotted-path parsing. This is how literal-dot keys are addressed: for `"a.b" = 1`, GetValuePath("a.b") returns 1, whereas GetValue("a.b") looks for a nested object `a` with key `b`. Passing several segments descends the tree segment by segment (GetValuePath("a", "b") == GetValue("a.b")).
func (*Config) HasPathSegments ¶
HasPathSegments reports whether a value exists at the given explicit path segments (the segmented analogue of Config.HasPath).
func (*Config) Render ¶
func (c *Config) Render(opts RenderOptions) string
Render serialises the config using the given options.
func (*Config) WithFallback ¶
WithFallback returns a new Config in which values missing from c are taken from fallback. Two objects at the same path deep-merge with c winning; anything else in c overrides the fallback outright. Neither input is mutated.
type ConfigValue ¶
type ConfigValue struct {
// contains filtered or unexported fields
}
ConfigValue is a single resolved HOCON value.
func NewArray ¶
func NewArray(elems ...*ConfigValue) *ConfigValue
NewArray returns an array value over the given elements.
func NewObjectOf ¶
func NewObjectOf(entries map[string]*ConfigValue) *ConfigValue
NewObjectOf returns an object value populated from entries (copied).
func (*ConfigValue) Elements ¶
func (v *ConfigValue) Elements() []*ConfigValue
Elements returns an array value's elements, or nil for non-array values.
func (*ConfigValue) Fields ¶
func (v *ConfigValue) Fields() map[string]*ConfigValue
Fields returns a shallow copy of an object value's entries. It returns nil for non-object values.
func (*ConfigValue) Type ¶
func (v *ConfigValue) Type() ConfigValueType
Type reports the value's type.
func (*ConfigValue) Unwrap ¶
func (v *ConfigValue) Unwrap() any
Unwrap returns the value as a native Go value: nil, bool, float64, string, []any or map[string]any.
type ConfigValueType ¶
type ConfigValueType int
ConfigValueType classifies a ConfigValue.
const ( NullType ConfigValueType = iota BooleanType NumberType StringType ArrayType ObjectType )
The value types HOCON can hold. They mirror JSON plus HOCON's distinction between the six is otherwise identical to JSON.
func (ConfigValueType) String ¶
func (t ConfigValueType) String() string
String names the type (useful in error messages and tests).
type EnvLookup ¶
EnvLookup resolves a substitution name against the environment when it is not found in the config, mirroring os.LookupEnv. It is an injectable seam.
type IncludeResolver ¶
IncludeResolver resolves an `include` directive to the text of the included document. kind is one of "file", "url" or "classpath"; name is the target. It is an injectable seam so callers (and tests) can supply content without touching the filesystem.
type Option ¶
type Option func(*options)
Option customises Parse.
func WithIncludeResolver ¶
func WithIncludeResolver(r IncludeResolver) Option
WithIncludeResolver overrides how `include` directives are resolved.
type ParseError ¶
ParseError describes a lexical or syntactic failure, with 1-based position.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
type PathError ¶
PathError wraps ErrMissing or ErrWrongType with the offending path.
type RenderOptions ¶
type RenderOptions struct {
// JSON emits strict JSON (quoted keys, colons, commas) instead of HOCON.
JSON bool
// Indent is the per-level indentation string; empty means two spaces.
Indent string
}
RenderOptions controls serialisation.
type ResolveError ¶
type ResolveError struct {
Msg string
}
ResolveError describes a failure while resolving substitutions (unresolved required substitution, or a substitution cycle).
func (*ResolveError) Error ¶
func (e *ResolveError) Error() string