今天工作中碰到的问题,要求修改此配置文件,没看出来是什么格式,用了下面的思路:
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)
如对本文有疑问, 点击进行留言回复!!
VSCode1.4 搭建Golang的开发调试环境(遇到很多问题)
网友评论