go-nacelle / nacelle

The Go service framework.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Env Sourcer slices

paulmeier opened this issue · comments

Is it possible to get a slice of string from an env var? Using env:"list" default:"'blue', 'red', 'green'" would not work. What I need is a []string specifically.

By default you can JSON-encode any of the values. Supplying ["blue", "red", "green"] should deserialize into a []string. The structtags could then be env:"list" default:"{\"blue\", \"red\", \"green\"}".

Does that work or do you need special value parsing logic?

I've tried to use the basic JSON encoded example you provided but it responds with an error about type coercion:

returned a fatal error (failed to initialize painting (failed to load config (default value for field 'List' cannot be coerced into the expected type)

From this example:

type Paints struct {
    List []string `env:"list" default:"{\"blue\", \"red\", \"green\"}"`
}

Thats really all I need, nothing special!

Oops, sorry! I had a typo in the suggestion. Here's a full working example:

package main

import (
	"fmt"

	"github.com/go-nacelle/nacelle"
)

type PaintsInitializer struct{}

type Paints struct {
	List []string `env:"list" default:"[\"blue\", \"red\", \"green\"]"`
}

func (i *PaintsInitializer) Init(config nacelle.Config) error {
	p := &Paints{}
	if err := config.Load(p); err != nil {
		return err
	}

	fmt.Printf("> %#v\n", p.List)
	return nil
}

func setup(processes nacelle.ProcessContainer, services nacelle.ServiceContainer) error {
	processes.RegisterInitializer(&PaintsInitializer{})
	return nil
}

func main() {
	nacelle.NewBootstrapper("example", setup).BootAndExit()
}

Notice [] instead of {} in the default.

Cool that works! Thanks!