parent
47dde8e9ed
commit
e374a8a3e1
|
|
@ -0,0 +1,87 @@
|
|||
package modules
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
db_host string
|
||||
db_port string
|
||||
db_username string
|
||||
db_password string
|
||||
db_name string
|
||||
server_host string
|
||||
server_port string
|
||||
}
|
||||
|
||||
func Readconfig() string {
|
||||
c := config{} // 创建空的 config 结构体实例
|
||||
// 打开配置文件
|
||||
file, err := os.Open("./config.conf")
|
||||
if err != nil {
|
||||
fmt.Println("无法打开配置文件:", err)
|
||||
}
|
||||
defer file.Close()
|
||||
var dsn string // 存储数据库连接字符串
|
||||
|
||||
// 创建一个Scanner来读取文件内容
|
||||
scanner := bufio.NewScanner(file)
|
||||
|
||||
// 逐行读取文件
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
// 忽略空行和注释行
|
||||
if len(line) == 0 || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
// 解析配置项
|
||||
parts := strings.Split(line, "=")
|
||||
if len(parts) != 2 {
|
||||
fmt.Println("无效的配置项:", line)
|
||||
continue
|
||||
}
|
||||
key := strings.TrimSpace(parts[0])
|
||||
value := strings.TrimSpace(parts[1])
|
||||
|
||||
//根据需要处理配置项
|
||||
switch key {
|
||||
case "db_host":
|
||||
c.db_host = value
|
||||
fmt.Println("数据库地址:", value)
|
||||
case "db_port":
|
||||
c.db_port = value
|
||||
fmt.Println("数据库端口:", value)
|
||||
case "db_username":
|
||||
c.db_username = value
|
||||
fmt.Println("数据库用户名:", value)
|
||||
case "db_password":
|
||||
c.db_password = value
|
||||
fmt.Println("数据库密码:", value)
|
||||
case "db_name":
|
||||
c.db_name = value
|
||||
fmt.Println("数据库名:", value)
|
||||
case "server_host":
|
||||
c.server_host = value
|
||||
fmt.Println("主机:", value)
|
||||
case "server_port":
|
||||
c.server_port = value
|
||||
fmt.Println("端口:", value)
|
||||
// case "log_level":
|
||||
// fmt.Println("日志等级:", value)
|
||||
// case "log_file":
|
||||
// fmt.Println("日志路径:", value)
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
fmt.Println("读取配置文件时发生错误:", err)
|
||||
}
|
||||
//fmt.Println(c)
|
||||
dsn = c.db_username + ":" + c.db_password + "@tcp(" + c.db_host + ":" + c.db_port + ")/" + c.db_name
|
||||
//dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", c.db_username, c.db_password, c.db_host, c.db_port, c.db_name)
|
||||
fmt.Println(dsn)
|
||||
return dsn
|
||||
}
|
||||
Loading…
Reference in New Issue