hocon

package module
v0.0.0-...-6adbe6e Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: BSD-3-Clause Imports: 9 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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.

View Source
var ErrMissing = errors.New("path not found")

ErrMissing is returned (wrapped in a *PathError) when a path is absent.

View Source
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 Parse

func Parse(src string, opts ...Option) (*Config, error)

Parse lexes, parses, merges and resolves a HOCON document into a *Config.

func (*Config) GetBool

func (c *Config) GetBool(path string) (bool, error)

GetBool returns the boolean at path.

func (*Config) GetBytes

func (c *Config) GetBytes(path string) (int64, error)

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

func (c *Config) GetDuration(path string) (time.Duration, error)

GetDuration returns the duration at path. A bare number is milliseconds; a string may carry a unit suffix (`10s`, `5 min`, `100ms`, ...).

func (*Config) GetFloat

func (c *Config) GetFloat(path string) (float64, error)

GetFloat returns the number at path as a float64.

func (*Config) GetInt

func (c *Config) GetInt(path string) (int64, error)

GetInt returns the number at path truncated to an int64.

func (*Config) GetList

func (c *Config) GetList(path string) ([]*ConfigValue, error)

GetList returns the array elements at path.

func (*Config) GetObject

func (c *Config) GetObject(path string) (*Config, error)

GetObject returns the object at path wrapped in its own Config.

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) GetString

func (c *Config) GetString(path string) (string, error)

GetString returns the string at path.

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) HasPath

func (c *Config) HasPath(path string) bool

HasPath reports whether a value exists at the dotted path.

func (*Config) HasPathSegments

func (c *Config) HasPathSegments(segments ...string) bool

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) Root

func (c *Config) Root() *ConfigValue

Root returns the root object value.

func (*Config) WithFallback

func (c *Config) WithFallback(fallback *Config) *Config

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 NewBool

func NewBool(b bool) *ConfigValue

NewBool returns a boolean value.

func NewNull

func NewNull() *ConfigValue

NewNull returns a null value.

func NewNumber

func NewNumber(n float64) *ConfigValue

NewNumber returns a numeric value.

func NewObject

func NewObject() *ConfigValue

NewObject returns an (empty) object value.

func NewObjectOf

func NewObjectOf(entries map[string]*ConfigValue) *ConfigValue

NewObjectOf returns an object value populated from entries (copied).

func NewString

func NewString(s string) *ConfigValue

NewString returns a string value.

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

type EnvLookup func(name string) (string, bool)

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

type IncludeResolver func(kind, name string) (string, error)

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 WithEnv

func WithEnv(e EnvLookup) Option

WithEnv overrides environment-variable fallback for substitutions.

func WithIncludeResolver

func WithIncludeResolver(r IncludeResolver) Option

WithIncludeResolver overrides how `include` directives are resolved.

type ParseError

type ParseError struct {
	Msg  string
	Line int
	Col  int
}

ParseError describes a lexical or syntactic failure, with 1-based position.

func (*ParseError) Error

func (e *ParseError) Error() string

type PathError

type PathError struct {
	Path string
	Err  error
}

PathError wraps ErrMissing or ErrWrongType with the offending path.

func (*PathError) Error

func (e *PathError) Error() string

func (*PathError) Unwrap

func (e *PathError) Unwrap() error

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

Jump to

Keyboard shortcuts

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