Go加载配置文件

作者: 太阳上的雨天 分类: Go 发布时间: 2022-02-24 15:04

.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: %s\n host: %s\n username: %s\n password:%s\n database: %s\n port: %s\n", driver, host, username, password, database, port)
}

func main() {

    http.HandleFunc("/", HandlerConf)

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

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注