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

匿名 (未验证) 提交于 2019-12-03 00:03:02

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

  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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!