config

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2024 License: MIT Imports: 8 Imported by: 0

README

Config Library

A Go library for parsing configuration files in YAML, JSON, and TOML formats.

Dependencies

This project depends on the following libraries:

Installation

go get github.com/aiechoic/config

Suppose you have a config.yaml file in your project directory:

server1:
  port: 8080
  password: "123"
server2:
  port: 8081
  password: "321"

You can parse it like this:

package main

import (
	"fmt"
	"github.com/aiechoic/config"
	"github.com/aiechoic/ioc"
	"os"
)

type Server struct {
	Port     int    `yaml:"port"`
	Password string `yaml:"password" env:"SERVER_PASSWORD"`
}

func main() {

	file := "./config.yaml"

	c := ioc.NewContainer()

	// Load config data from file and set it to container
	config.LoadConfigFile(c, file)

	// Unmarshal config data from container
	server1 := config.MustUnmarshalConfig[Server](c, "server1")

	// Set environment variables, recover the original value "321"
	_ = os.Setenv("SERVER_PASSWORD", "111")

	server2 := config.MustUnmarshalConfig[Server](c, "server2")

	fmt.Printf("server1: %+v\n", *server1)
	fmt.Printf("server2: %+v\n", *server2)

	// Output:
	// server1: {Port:8080 Password:123}
	// server2: {Port:8081 Password:111}

}

More examples can be found in the examples directory.

License

This project is licensed under the MIT License - see the LICENSE file for details

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoadConfigData

func LoadConfigData(c *ioc.Container, parser Parser, data []byte)

func LoadConfigFile

func LoadConfigFile(c *ioc.Container, file string)

func MustUnmarshalConfig

func MustUnmarshalConfig[T any](c *ioc.Container, name string) *T

func ParseJSON

func ParseJSON[T any](data []byte, key string) (*T, error)

func ParseTOML

func ParseTOML[T any](data []byte, key string) (*T, error)

func ParseYAML

func ParseYAML[T any](data []byte, key string) (*T, error)

func UnmarshalConfig

func UnmarshalConfig[T any](c *ioc.Container, name string) (*T, error)

Types

type Parser

type Parser string
const (
	YAMLParser Parser = "yaml"
	JSONParser Parser = "json"
	TOMLParser Parser = "toml"
)

Directories

Path Synopsis
examples
json command
toml command
yaml command

Jump to

Keyboard shortcuts

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