config

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2022 License: Apache-2.0 Imports: 7 Imported by: 3

README

config GoDoc test Go Report Card codecov.io Maintainability Apache 2 licensed

Simple JSON configuration handling for server applications.

Refer to go package documentation for details.

Documentation

Overview

Package config provides structs and functions to create and modify a configuration store, containing key-value pairs where each key denotes a configuration and the corresponding value is a json string with the config information.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrKeyNotFound = errors.New("key not found")

Functions

This section is empty.

Types

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store represents a map of string keys and []byte values. In this case, the key is the configuration name and the value is the related config.

Example
package main

import (
	"context"
	"fmt"

	"gojini.dev/config"
)

func main() {
	store := config.New()
	cfgStr := `{"log": {"file": "example.log"}, "server": {"port": 8088}}`

	if e := store.LoadFromStr(context.Background(), cfgStr); e != nil {
		panic(e)
	}

	l := &struct {
		File string `json:"file"`
	}{File: "default.log"}

	if e := store.Get("log", l); e == nil {
		fmt.Println("log file:", l.File)
	}

	s := &struct {
		Port int `json:"port"`
	}{Port: 0}
	if e := store.Get("server", s); e == nil {
		fmt.Println("server port:", s.Port)
	}

}
Output:

log file: example.log
server port: 8088

func New

func New() *Store

New returns a config store that can hold a map of key and arbitarary config blob. The key is the name of the configuration that can be retrieved using the Get method once configuration is loaded.

func (*Store) Get

func (s *Store) Get(key string, config interface{}) error

Get retrieves the config specified by the key if exists. If the config cannot be parsed into the provided structure it returns an error.

func (*Store) Load

func (s *Store) Load(ctx context.Context, src io.Reader) error

Load loads the configuration using a io.Reader. The reader must point to a valid json stream of maps. An example configuration is:

{"log": {"file": "example.log"}, "server": {"port": 8088}}

this config has two keys, log and server with corresponding configuration which can be retreived using Get method.

Returns error if the configuration stream is not parsable in the above format.

func (*Store) LoadFromFile

func (s *Store) LoadFromFile(ctx context.Context, cfgFile string) error

LoadFromFile loads configuration from a file.

func (*Store) LoadFromStr

func (s *Store) LoadFromStr(ctx context.Context, cfg string) error

LoadFromStr loads configuration from a string.

Jump to

Keyboard shortcuts

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