Home [Shorts] Read Config files using Viper in Golang
Post
Cancel

[Shorts] Read Config files using Viper in Golang

Installation

1
go get github.com/spf13/viper

Write Config Files

app.env

1
2
3
DB_DRIVER="postgres"
DB_SOURCE="postgres://root:secret@localhost:5432/test_db?sslmode=disable"
SERVER_ADDRESS="0.0.0.0:3000"

you can also create config files in other extensions like yaml, json, TOML

Read Config Files

env/config.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package env

import "github.com/spf13/viper"

type Config struct {
  DBDriver      string	`mapstructure:"DB_DRIVER"`
  DBSource      string	`mapstructure:"DB_SOURCE"`
  ServerAddress string	`mapstructure:"SERVER_ADDRESS"`
}

func LoadConfig(path string) (config Config, err error) {
  viper.AddConfigPath(path)
  viper.SetConfigName("app") // your config file's name : [app].env
  viper.SetConfigType("env") // your config file's extension : app.[env]
  
  viper.AutomaticEnv()
  
  err = viper.ReadInConfig()
  if err != nil {
    return
  }
  err = viper.Unmarshal(&config)
  return
}

main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
  "testenv/env"
  "fmt"
  "reflect"
)

func main() {
  config, err := env.LoadConfig(".") // path of app.env
  if err != nil {
    log.Fatal("cannot read config: ", err)
  }
  values := reflect.ValueOf(config)
  typeOfFields := values.Type()
  for i := 0; i < values.NumField(); i++ {
    fmt.Printf(" %s : %v \n", typeOfFields.Field(i).Name, v.Field(i).Interface())
  }
}

Output

1
2
3
DBDriver : postgres
DBSource : postgres://root:secret@localhost:5432/test_db?sslmode=disable
ServerAddress : 0.0.0.0:3000
This post is licensed under CC BY 4.0 by the author.

[Docker] Docker를 사용하여 postgreSQL 서버를 띄워보자(1)

[짧] Query Parameter vs Path parameter