Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 在文件中的特定位置后插入字符串_Go - Fatal编程技术网

Go 在文件中的特定位置后插入字符串

Go 在文件中的特定位置后插入字符串,go,Go,我有这个档案: upstream frontends { server service-example1.example.com; server service-example2.example.com; } server { listen 80; location / { proxy_pass http://frontends; } } 我想做的是删除和添加上游前端部分中的行。删除线路非常容易: package main import (

我有这个档案:

upstream frontends {
    server service-example1.example.com;
    server service-example2.example.com;
}

server {
  listen 80;

  location / {
      proxy_pass http://frontends;
  }
}
我想做的是删除和添加上游前端部分中的行。删除线路非常容易:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
)

func main() {
    content, err := ioutil.ReadFile("nginx.conf")
    if err != nil {
        panic(err)
    }

    lines := bytes.Replace(content, []byte("server service-example1.example.com;"), []byte(""), 1)
    fmt.Println(string(lines))
    err = ioutil.WriteFile("nginx.conf", lines, 0644)
    if err != nil {
        panic(err)
    }
}
然而,我发现添加我再次删除的同一行要困难得多。我的场景是,我想删除包含“server service-example2.example.com;”的行,重新加载nginx conf。稍后,我想在它的上一个位置添加相同的行,然后再次重新加载nginx

我发现很难获得文件中要使用*(f file)WriteAt再次添加行的确切字节位置。我一直在看这个例子,但找不出一个好的方法


有人知道我该如何解决这个问题吗?

最好是写一个解析器/词法分析器。为简单和快速起见,您是否考虑过不删除行,而是用一些注释替换它,以便在重新插入数据时能够再次替换?由于您无法将字节“插入”到文件中,因此通常更容易(尤其是像这样的小文件)读取文件,根据需要操纵文本,并作为一个整体编写一个新文件。这还允许您编写一个完整的临时文件,并以原子方式替换原始文件,而不是冒原始文件损坏的风险。@mh cbon感谢您的想法,注释掉行可能是最简单的方法。最好,您应该编写一个解析器/词法分析器。为简单和快速起见,您是否考虑过不删除行,而是用一些注释替换它,以便在重新插入数据时能够再次替换?由于您无法将字节“插入”到文件中,因此通常更容易(尤其是像这样的小文件)读取文件,根据需要操纵文本,并作为一个整体编写一个新文件。这还允许您编写一个完整的临时文件,并以原子方式替换原始文件,而不是冒原始文件损坏的风险。@mh cbon感谢您的想法,注释掉行可能是解决此问题最简单的方法