欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Golang读取并修改非主流配置文件

程序员文章站 2022-07-01 08:42:57
今天工作中碰到的问题,要求修改此配置文件,没看出来是什么格式,用了下面的思路: 用Go代码修改如上所示的配置文件,如 字段的值,步骤如下: 获取键 的值; 将`radius_db = "test13"`整体包装成字符串; 包装新字符串; 整体替换。 主要实现代码: Go // 根据路径获取文件 co ......

今天工作中碰到的问题,要求修改此配置文件,没看出来是什么格式,用了下面的思路:

  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)