Skip to content

Question : Best way to pass default struct into viperΒ #653

@matthieugouel

Description

@matthieugouel

Hello everyone,

I hope there is no duplicate for that.
I'm new to Golang therefore to viper. My use case is to have a structure as a default value, that can be overridden via an other way (env variable, ...). I want to avoid using SetDefault since it could be a lot of config variable in nested configuration.

I managed to to that by marshaling my structure with JSON and than passing the byte slice into ReadConfig .

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/spf13/viper"
)

// Config : Application configuration
type Config struct {
	Jwt JwtConfig
}

// JwtConfig : JWT configuration
type JwtConfig struct {
	Secret string
}

func main() {

	cfg := Config{
		Jwt: JwtConfig{
			Secret: "helicopter",
		},
	}

	viper.SetConfigType("json")
	cfgJSON, err := json.Marshal(cfg)
	if err != nil {
		panic(err)
	}

	viper.ReadConfig((bytes.NewBuffer(cfgJSON)))

	viper.SetEnvPrefix("TEST")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv()

	fmt.Println(viper.Get("jwt.secret"))
}

My question is : is it the prefered way to do it ? Or maybe is there a more efficient way to do that without JSON/YAML marshalling ?

Best,
Matthieu.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions