Fool's blog Fool's blog
首页
  • Ansible
  • Jenkins
  • Docker
  • Kubernetes
  • Linux常用命令
  • Git
  • Nginx
  • PVE
  • Samaba
  • Python
  • Go
GitHub (opens new window)

The Fool

运维萌新
首页
  • Ansible
  • Jenkins
  • Docker
  • Kubernetes
  • Linux常用命令
  • Git
  • Nginx
  • PVE
  • Samaba
  • Python
  • Go
GitHub (opens new window)
  • Python

  • Go

    • viper
  • 编程语言
  • Go
The Fool
2025-12-20

viper

# viper

使用viper读取yml文件内容

go get -u github.com/spf13/viper
1

想看目录结构

1735648190134.png

config.yml

app:
  name: zsan
  port: :3000

database:
  dsn: root:111111@tcp(127.0.0.1:3306)/zdb?charset=utf8mb4&parseTime=True&loc=Local
  SetMaxIdleConns: 10
  SetMaxOpenConns: 100
1
2
3
4
5
6
7
8

config.go

package config

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
)

type Config struct {
	App struct {
		Name string
		Port string
	}

	Database struct {
		Dsn             string
		SetMaxIdleConns int
		SetMaxOpenConns int
	}
}

var MyConfig *Config

func InitConfig() {
	viper.SetConfigName("config")
	viper.SetConfigType("yml")
	viper.AddConfigPath("./config")
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalf("Fail read config file: %s \n", err)
	}
	MyConfig = &Config{}
	err = viper.Unmarshal(MyConfig)
	if err != nil {
		log.Fatalf("Fail unmarshal config file: %s \n", err)
	}

}

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39

main.go

package main

import (
	"fmt"
	"my_go_test/config"
)

func main() {
	config.InitConfig()
	fmt.Println(config.MyConfig.App.Name)
}

1
2
3
4
5
6
7
8
9
10
11
12
#viper
faker

← faker

最近更新
01
Jenkins基础
12-19
02
Jenkins实践
12-19
03
Ansible基础
11-02
更多文章>
Theme by Vdoing | Copyright © 2024-2025 The Fool
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式