Golang读取并修改非主流配置文件
2024-09-02 13:45:36
今天工作中碰到的问题,要求修改此配置文件,没看出来是什么格式,用了下面的思路:
mysql {
# If any of the files below are set, TLS encryption is enabled
tls {
ca_file = "/etc/ssl/certs/my_ca.crt"
ca_path = "/etc/ssl/certs/"
certificate_file = "/etc/ssl/certs/private/client.crt"
private_key_file = "/etc/ssl/certs/private/client.key"
cipher = "DHE-RSA-AES256-SHA:AES128-SHA"
tls_required = yes
tls_check_cert = no
tls_check_cert_cn = no
}
# If yes, (or auto and libmysqlclient reports warnings are
# available), will retrieve and log additional warnings from
# the server if an error has occured. Defaults to 'auto'
warnings = auto
}
postgresql {
# unlike MySQL, which has a tls{} connection configuration, postgresql
# uses its connection parameters - see the radius_db option below in
# this file
# Send application_name to the postgres server
# Only supported in PG 9.0 and greater. Defaults to no.
send_application_name = yes
}
# Connection info:
#
server = "127.0.0.1"
port = 5432
login = "testuser13"
password = "Tpass123"
# Database table configuration for everything except Oracle
radius_db = "test13"
# If you are using Oracle then use this instead
# radius_db = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=your_sid)))"
用Go代码修改如上所示的配置文件,如radius_db
字段的值,步骤如下:
github.com/go-ini/ini
获取键radius_db
的值;fmt.Sprintf()
将radius_db = "test13"
整体包装成字符串;fmt.Sprintf()
包装新字符串;strings.Replace()
整体替换。
主要实现代码:
// 根据路径获取文件
configFile := "./sql.conf"
configContent, err := ioutil.ReadFile(configFile)
// 加载配置文件,跳过无法解析的行;设置key/value分隔符为"="
cfg, err := ini.LoadSources(ini.LoadOptions
{SkipUnrecognizableLines:true, KeyValueDelimiters:"="}, configFile)
// 获取"radius_db"的值
sqlDBName := cfg.Section("").Key("radius_db").String()
// newName指要修改的新值
sqlDBNameOld := fmt.Sprintf(`radius_db = "%s"`, sqlDBName)
sqlDBNameNew := fmt.Sprintf(`radius_db = "%s"`, newName)
// 替换并写入
newConfig := strings.Replace(string(configContent), sqlDBNameOld, sqlDBNameNew, 1)
// 写入文件
err = ioutil.WriteFile(configFile, []byte(newConfig), 0644)
最新文章
- windows下mysql客户端输入中文显示??解决方法
- android版高仿淘宝客户端源码V2.3
- HDU5800 To My Girlfriend 背包计数dp
- .net和MVC中的json值和List<;T>;和DataTable的一些转换
- PHP中使用函数array_merge()合并数组
- 用css样式,为表格加入边框
- ASP.NET 5 Hello World
- Problem - D - Codeforces Fix a Tree
- 工作中对数组的一些处理,整理(结合underscore.js)
- Beta冲刺第四天
- python基础-循环
- [Swift]LeetCode198. 打家劫舍 | House Robber
- 说一说MVC的CustomHandlerErrorAttribute(五)
- Tomcat 本地运行正常,服务器部署后乱码问题
- HYSBZ 2743 (树状数组) 采花
- 003.Heartbeat MySQL双主复制
- c#读取文本并生成txt
- js事件监听
- 兼容IE8以下,获取className节点的元素(document.getElementsByClassName()兼容写法)。
- vue element-ui 通过v-for渲染的el-form-item组件,使用自带的表单验证