yamlcfg

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2024 License: MIT Imports: 5 Imported by: 0

README

yamlcfg

yamlcfg is a wrapper around the gopkg.in/yaml.v3 library and provides a convient way to configure Golang applications with YAML and environment variables.

The library can also automatically call Validate functions if present on the given config struct.

Installation

To install, run:

go get github.com/aranw/yamlcfg

License

The yamlcfg package is licensed under the MIT. Please see the LICENSE file for details.

Example

package main

import (
	"log/slog"

	"github.com/aranw/yamlcfg"
)

type Config struct {
	LogLevel string `yaml:"log_level"`
}

func (c *Config) Validate() error {
    validLevels := [...]string{"debug", "info", "error"}

	validLevel := slices.ContainsFunc(validLevels[:], func(s string) bool {
		return strings.EqualFold(s, c.Log.Level)
	})

	if c.Log.Level == "" {
		c.Log.Level = "info"
	} else if !validLevel {
		return errors.New("invalid log level provided")
	}

    return nil
}

func main() {
	cfg, err := yamlcfg.Load[Config]("config.yaml")
	if err != nil {
		slog.Error("loading yaml config", "err", err)
		return
	}

	_ = cfg.LogLevel
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse[T any](path string) (*T, error)

Parse takes the given path and attempts to read and unmarshal the config The given config will also be validated if it has a Validate function on it

Example
package main

import (
	"log/slog"

	"github.com/aranw/yamlcfg"
)

type Config struct {
	LogLevel string `yaml:"log_level"`
}

func main() {
	cfg, err := yamlcfg.Parse[Config]("config.yaml")
	if err != nil {
		slog.Error("loading yaml config", "err", err)
		return
	}

	_ = cfg.LogLevel
}
Output:

func ParseFS

func ParseFS[T any](fs embed.FS, path string) (*T, error)

ParseFS attempts to load the given path and config from a embed.FS

Example
package main

import (
	"embed"
	"log/slog"

	"github.com/aranw/yamlcfg"
)

type Config struct {
	LogLevel string `yaml:"log_level"`
}

//go:embed testdata
var testdata embed.FS

func main() {
	cfg, err := yamlcfg.ParseFS[Config](testdata, "config.yaml")
	if err != nil {
		slog.Error("loading yaml config", "err", err)
		return
	}

	_ = cfg.LogLevel
}
Output:

func UnmarshalConfig

func UnmarshalConfig[T any](cfg *T, data []byte) error

UnmarshalConfig takes the provided yaml data and unmarshals it into the provided config struct. It will return an error if the decoding fails or if the yaml data is not in the expected format. It will also expand any environment variables in the yaml data

Types

This section is empty.

Jump to

Keyboard shortcuts

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