Golang : 替换配置文件中的参数值的例子

337 阅读1分钟

把这个放在这里,供我以后参考。在本教程中,我们将探讨如何读入一个配置(文本)文件,替换某个参数的值并将其写回(更新)到文件中。

基本上,这个简单的程序所做的是将整个配置(文本)文件转换成一个片断,扫描我们想要改变的参数,更新参数的值并写回文件。

 package main

 import (
  "fmt"
  "strings"
 )

 func main() {

  input, err := ioutil.ReadFile(configFilename)
  if err != nil {
 log.Println(err)
  }

  // split into a slice
  lines := strings.Split(string(input), "\n")

  fmt.Println("before : ", lines)

  // assuming that we want to change the value of thirdItem from 3 to 100
  replacementText := "thirdItem = 100"

  for i, line := range lines {
 if equal := strings.Index(line, "thirdItem"); equal == 0 {
 // update to the new value
 lines[i] = replacementText
 }
  }

  fmt.Println("after : ", lines)

  // join back before writing into the file
  linesBytes := []byte(strings.Join(lines, "\n"))

  //the value will be UPDATED!!!
  if err = ioutil.WriteFile(configFilename, linesBytes, 0666); err != nil {
 log.Println(err)
  }
 }

你可以在不修改任何文件的情况下玩一个演示,play.golang.org/p/G8RKWdfh5…

希望这对你有帮助,祝你编码愉快

参考资料:

www.socketloop.com/references/…

www.socketloop.com/tutorials/g…