import "toolman.org/text/interp"
go get toolman.org/text/interp
Package interp provides a simple string variable interpolator.
cat.go interp.go token.go varfmt.go
type Interpolator struct {
// contains filtered or unexported fields
}
An Interpolator is used to interpolate variable expressions embedded within
a body of text. By default, variable expression are of the form ${varname}
and use a backslash as an escape character. An alternate expression format
may also be specified by calling NewWithFormat
.
For both Interpolator constructors, the caller must provide a Resolver for resolving variable names to their associated values.
func New(g Resolver) *Interpolator
New returns a new Interpolator for the given Resolver using the default variable expression format.
func NewWithFormat(g Resolver, b *VarFormat) *Interpolator
NewWithFormat returns a new Interpolator for the given Resolver and specified VarFormat.
func (*Interpolator) Interpolate
func (i *Interpolator) Interpolate(s string) (string, error)
Interpolate repeatedly searchs the given string for the inner-most variable expression replacing each one with its associated value acquired from the Interpolator's Resolver. If the Resolver returns an error, or if its returned Value cannot be stringified, an empty string and error are returned.
Interpolate continues this process until it no longer finds a variable expression in the provided string, or an error is encountered.
type Resolver interface {
// Resolve returns the Value associated with the given variable. If no Value
// is found, Resolve may return nil and an error. Any error returned here
// will ultimately be returned by Replace.
Resolve(variable string) (value Value, err error)
}
Resolver is used by Interpolator to lookup values for interpolated variables.
type Value interface{}
Value is an enpty interface type returned by a Resolvers' Resolve method. Its underlying value should be something that is ultimately stringable with the following guidelines:
* string values are used directly
* String() is called for fmt.Stringer values
* If Value is an encoding.TextMarshaler, its MarshalText()
method is called and the results are converted to a string
* Otherwise the value is passed through fmt.Sprintf("%v")
type VarFormat struct {
Begin string // The string token that preceeds a variable name
End string // The string token that follows a variable name
Escape byte // The escale character used to skip one of the above tokens
}
VarFormat defines what a variable expression should look like.