yaml

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2024 License: MIT Imports: 4 Imported by: 1

Documentation

Overview

Package yaml provides a YAML loader for xload.

Example
package main

import (
	"context"
	"os"

	"github.com/gojekfarm/xtools/xload"
	"github.com/gojekfarm/xtools/xload/providers/yaml"
)

func main() {
	// This example shows how to load values from a YAML file.
	//
	// The example YAML file looks like this:
	//
	// NAME: xload
	// VERSION: 1.1

	ctx := context.Background()
	cfg := struct {
		Name    string `env:"NAME"`
		Version string `env:"VERSION"`
	}{}

	f, err := os.Open("example.yaml")
	if err != nil {
		panic(err)
	}

	loader, err := yaml.NewLoader(f, "_")
	if err != nil {
		panic(err)
	}

	err = xload.Load(ctx, &cfg, loader)
	if err != nil {
		panic(err)
	}
}
Output:

Example (NestedStruct)
package main

import (
	"context"
	"os"

	"github.com/gojekfarm/xtools/xload"
	"github.com/gojekfarm/xtools/xload/providers/yaml"
)

func main() {
	// This example shows how to load values from a YAML file into a nested struct.
	//
	// The example YAML file looks like this:
	//
	// NAME: xload
	// VERSION: 1.1
	// DATABASE:
	//   HOST: localhost
	//   PORT: 5432

	ctx := context.Background()
	cfg := struct {
		Name    string `env:"NAME"`
		Version string `env:"VERSION"`
		DB      struct {
			Host string `env:"HOST"`
			Port int    `env:"PORT"`
		} `env:",prefix=DATABASE_"`
	}{}

	f, err := os.Open("example.yaml")
	if err != nil {
		panic(err)
	}

	// IMPORTANT: The prefix for nested struct is specified in
	// the struct tag. In this case, the prefix is DATABASE_.
	// The separator specified in the NewLoader should match
	// the prefix. In this case, the separator is "_".
	loader, err := yaml.NewLoader(f, "_")
	if err != nil {
		panic(err)
	}

	err = xload.Load(ctx, &cfg, loader)
	if err != nil {
		panic(err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewFileLoader

func NewFileLoader(path, sep string) (_ xload.MapLoader, err error)

NewFileLoader reads YAML from the given file and returns a xload.Loader Nested keys are flattened using the given separator.

IMPORTANT: The separator must be consistent with prefix used in the struct tags.

func NewLoader

func NewLoader(r io.Reader, sep string) (xload.MapLoader, error)

NewLoader reads YAML from the given io.Reader and returns a xload.Loader Nested keys are flattened using the given separator.

IMPORTANT: The separator must be consistent with prefix used in the struct tags.

Types

This section is empty.

Jump to

Keyboard shortcuts

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