栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go加载配置文件

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go加载配置文件

创作不易感谢支持。
一条主写Go和PHP的小菜鸟。平常有时间喜欢自己写点东西,如有不对的地方,欢迎大佬指点。 个人博客:太阳上的雨天 地址:http://blog.caixiaoxin.cn 善于分享,希望有助他人. 非常感谢各位大佬的关注和支持

.ini 方式

conf/conf.ini

driver=mysql
host=127.0.0.1
username=root
password=root
database=test
port=3306

conf/conf.go

package conf

import (
	"bufio"
	"io"
	"os"
	"strings"
)

//InitConfig 初始化项目配置
func InitConfig(path string) map[string]string {
	config := make(map[string]string)

	f, err := os.Open(path)
	defer f.Close()
	if err != nil {
		panic(err)
	}

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}
		s := strings.TrimSpace(string(b))
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}
		key := strings.TrimSpace(s[:index])
		if len(key) == 0 {
			continue
		}
		value := strings.TrimSpace(s[index+1:])
		if len(value) == 0 {
			continue
		}
		config[key] = value
	}
	return config
}

main.go

package main

import (
	"fmt"
	"net/http"
	"omp-cashier/conf"
)

var ConfigFilePath = "conf/conf.ini"

func HandlerConf(w http.ResponseWriter, r *http.Request) {
	config := conf.InitConfig(ConfigFilePath)

	driver := config["driver"]
	host := config["host"]
	username := config["username"]
	password := config["password"]
	database := config["database"]
	port := config["port"]

	fmt.Printf("driver: %sn host: %sn username: %sn password:%sn database: %sn port: %sn", driver, host, username, password, database, port)
}

func main() {
	

	http.HandleFunc("/", HandlerConf)

	http.ListenAndServe(":9999", nil)
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/904795.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号