Skip to content

Instantly share code, notes, and snippets.

@eftakhairul
Forked from chazcheadle/config.go
Created January 28, 2019 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eftakhairul/51e4bc7797e4e596df3334be4bf2de03 to your computer and use it in GitHub Desktop.
Save eftakhairul/51e4bc7797e4e596df3334be4bf2de03 to your computer and use it in GitHub Desktop.
Golang Viper config read into struct
package main
import (
"fmt"
"github.com/spf13/viper"
)
// Create private data struct to hold config options.
type config struct {
Hostname string `yaml:"hostname"`
Port string `yaml:"port"`
}
// Create a new config instance.
var (
conf *config
)
// Read the config file from the current directory and marshal
// into the conf config struct.
func getConf() *config {
viper.AddConfigPath(".")
viper.SetConfigName("config")
err := viper.ReadInConfig()
if err != nil {
fmt.Printf("%v", err)
}
conf := &config{}
err = viper.Unmarshal(conf)
if err != nil {
fmt.Printf("unable to decode into config struct, %v", err)
}
return conf
}
// Initialization routine.
func init() {
// Retrieve config options.
conf = getConf()
}
// Main program.
func main() {
// Print the config options from the new conf struct instance.
fmt.Printf("Hostname: %v\n", conf.Hostname)
fmt.Printf("Port: %v\n", conf.Port)
}
hostname: "localhost"
port: "9001"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment