Go 获取工作目录并读取配置文件

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/spf13/viper"
	"go.uber.org/zap"
)

var (
	logger *zap.Logger
	pwd    string
	config *viper.Viper
)

func init() {
	logger, _ = zap.NewProduction()

	func() {
		if ex, err := os.Executable(); err != nil {
			logger.Fatal("Failed to get the working directory", zap.Error(err))
		} else {
			pwd = filepath.Dir(ex)
		}
	}()

	func() {
		config = viper.New()
		config.AddConfigPath(pwd)
		config.SetConfigName("config")
		config.SetConfigType("yaml")
		if err := config.ReadInConfig(); err != nil {
			logger.Fatal("Failed to read the configuration file. Procedure", zap.Error(err))
		}
	}()
}
posted @ 2022-03-24 17:12  liy36  阅读(249)  评论(0)    收藏  举报