Coder Social home page Coder Social logo

go-conf's People

Contributors

thomasobenaus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

go-conf's Issues

Error messages for structs are misleading

Code

package main

import (
	"fmt"
	"os"
	"time"

	config "github.com/ThomasObenaus/go-conf"
	"github.com/ThomasObenaus/go-conf/interfaces"
	"github.com/davecgh/go-spew/spew"
)

type PrimitiveTypes struct {
	Field6 time.Time `cfg:"{'name':'aa'}"`
}

func main() {

	args := []string{
		"--aa=dd", //2021-02-22 12:34:00 +0000 UTC",
	}

	// 1. Create an instance of the config struct that should be filled
	cfg := PrimitiveTypes{}

	// 2. Create an instance of the config provider which is responsible to read the config
	// from defaults, environment variables, config file or command line
	prefixForEnvironmentVariables := "MY_APP"
	nameOfTheConfig := "MY_APP"
	provider, err := config.NewConfigProvider(
		&cfg,
		nameOfTheConfig,
		prefixForEnvironmentVariables,
		config.Logger(interfaces.DebugLogger),
	)
	if err != nil {
		panic(err)
	}

	// 3. Start reading and fill the config parameters
	err = provider.ReadConfig(args)
	if err != nil {
		fmt.Println("##### Failed reading the config")
		fmt.Printf("Error: %s\n", err.Error())
		fmt.Println("Usage:")
		fmt.Print(provider.Usage())
		os.Exit(1)
	}

	fmt.Println("##### Successfully read the config")
	fmt.Println()
	spew.Dump(cfg)
}

Returns

Debug] [Extract-()] structure-type=*main.PrimitiveTypes definition=name:"",desc:"",default:<nil> (<nil>),required=true
[Debug] [Process-(Field6)] field-type=time.Time
[Debug] [Process-(Field6)] parsed config entry=name:"aa",desc:"",default:<nil> (<nil>),required=true. Is primitive=false.
[Debug] [Extract-(Field6)] structure-type=*time.Time definition=name:"aa",desc:"",default:<nil> (<nil>),required=true
[Debug] [Process-(Field6.wall)] field-type=uint64
[Info] [Process-(Field6.wall)] no tag found entry will be skipped.
[Debug] [Process-(Field6.ext)] field-type=int64
[Info] [Process-(Field6.ext)] no tag found entry will be skipped.
[Debug] [Process-(Field6.loc)] field-type=*time.Location
[Info] [Process-(Field6.loc)] no tag found entry will be skipped.
[Debug] [Extract-(Field6)] added 0 configTags.
##### Failed reading the config
Error: unknown flag: --aa

Actual Result

Error: unknown flag: --aa

Expected Result

Error: No annotations given for fields of struct on field ('Field6'). Please annotate the relevant fields or provide a mapping function.

Conf returns no value for complex types read form yaml

To reproduce

this test can be used

func Test_Things(t *testing.T) {
	// GIVEN
	entry := NewEntry("things", "A list of things [{'user':'user1','age':25},{'user':'user2','age':55}]. The user has to be unique.", Default(""))
	type myCfg struct {
	}

	cfg := myCfg{}
	provider, err := NewConfigProvider(&cfg, "MyConfig", "MY_APP", CustomConfigEntries([]Entry{entry}))
	require.NoError(t, err)

	args := []string{
		"--config-file=test/data/things.yaml",
	}

	// WHEN
	err = provider.ReadConfig(args)
	require.NoError(t, err)

	// THEN
	things := provider.Get("things")
	assert.NotEmpty(t, things)
	assert.Equal(t, []interface{}{
		map[interface{}]interface{}{"age": 25, "user": "user1"},
		map[interface{}]interface{}{"age": 55, "user": "user2"},
	}, things)
}

Nil ptr when having non annotated non primitive types as part of the config struct

When running this test

func Test_extractConfigTagsOfStruct_NonPrimitiveWithoutAnnotation(t *testing.T) {
	// GIVEN
	type nested struct {
		FieldA string
	}

	type my struct {
		Field1 string `cfg:"{'name':'field-1','desc':'a string field','default':'field-1 default'}"`
		Field3 nested
	}
	strct := my{}

	// WHEN
	cfgTags, errNoPointer := extractConfigTagsOfStruct(&strct, interfaces.NoLogging, "", configTag{})

	// THEN
	require.NoError(t, errNoPointer)
	require.Len(t, cfgTags, 5)
}

a nilptr access is happening

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
	panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x60 pc=0x67bc97]

goroutine 6 [running]:
testing.tRunner.func1.2(0x6d2520, 0x8fa2d0)
	/usr/local/go/src/testing/testing.go:1143 +0x332
testing.tRunner.func1(0xc000001b00)
	/usr/local/go/src/testing/testing.go:1146 +0x4b6
panic(0x6d2520, 0x8fa2d0)
	/usr/local/go/src/runtime/panic.go:965 +0x1b9
github.com/ThomasObenaus/go-conf.processAllConfigTagsOfStruct(0x6b5100, 0xc00007c640, 0x7393f8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
	/home/winnietom/work/code/go-conf/extract.go:241 +0x8f7
github.com/ThomasObenaus/go-conf.extractConfigTagsOfStruct(0x6b5100, 0xc00007c640, 0x7393f8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
	/home/winnietom/work/code/go-conf/extract.go:168 +0x2e8
github.com/ThomasObenaus/go-conf.Test_extractConfigTagsOfStruct_NonPrimitiveWithoutAnnotation(0xc000001b00)
	/home/winnietom/work/code/go-conf/extract_test.go:418 +0x98
testing.tRunner(0xc000001b00, 0x739330)
	/usr/local/go/src/testing/testing.go:1193 +0xef
created by testing.(*T).Run
	/usr/local/go/src/testing/testing.go:1238 +0x2b3

Required parameters can be emtpy

package main

import (
	"fmt"
	"os"

	config "github.com/ThomasObenaus/go-conf"
	"github.com/davecgh/go-spew/spew"
)

// Just a struct with the desired config parameters has to be defined.
// Each field has to be annotated with the cfg struct tag
//	`cfg:{'name':'<name of the parameter>','desc':'<description>'}`
// The tag has to be specified as json structure using single quotes.
// Mandatory fields are 'name' and 'desc'.
type MyFontConfig struct {
	Color string `cfg:"{'name':'color','desc':'The value of the color as hexadecimal RGB string.'}"`
	Name  string `cfg:"{'name':'name','desc':'Name of the font to be used.'}"`
	Size  int    `cfg:"{'name':'size','desc':'Size of the font.'}"`
}

func main() {

	args := []string{}

	// 1. Create an instance of the config struct that should be filled
	cfg := MyFontConfig{}

	// 2. Create an instance of the config provider which is responsible to read the config
	// from defaults, environment variables, config file or command line
	prefixForEnvironmentVariables := "MY_APP"
	nameOfTheConfig := "MY_APP"
	provider, err := config.NewConfigProvider(
		&cfg,
		nameOfTheConfig,
		prefixForEnvironmentVariables,
	)
	if err != nil {
		panic(err)
	}

	// 3. Start reading and fill the config parameters
	err = provider.ReadConfig(args)
	if err != nil {
		fmt.Println("##### Failed reading the config")
		fmt.Printf("Error: %s\n", err.Error())
		fmt.Println("Usage:")
		fmt.Print(provider.Usage())
		os.Exit(1)
	}

	fmt.Println("##### Successfully read the config")
	fmt.Println()
	spew.Dump(cfg)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.