Hello i want to append new lines where i want in a .go file for example
i want to append fmt.Println(“new line”) before fmt.Println("Hello, world)
and also i want to add new line after “fmt” for example “myPackage”,
Can you provide more context around what you’re trying to do and why? If you have a before and after of what you want the file to look like, using diff to create a patch and then applying it would probably be easiest.
Otherwise, are you allowed to change the original file? If so, you could do it with a template: Go Playground - go.dev
If not, you’ll have to parse the original source into an AST and then programmatically rewrite the AST with a package like Fatih Arslan’s astrewrite package.
package main
import (
"log"
"strings"
"io/ioutil"
)
func main() {
input, err := ioutil.ReadFile("file.go")// here i open the file i want to modify
if err != nil {
log.Fatalln(err)
}
lines := strings.Split(string(input), "\n")// Here i store are lines that are in the file
for i, line := range lines { // Here i loop trought all file lines
if strings.Contains(line, "import (") || strings.Contains(line, "import(") {//here i search for the line i want to replace and add
lines[i] = `import (
"myPackage"`//here i replace the line with the new data
}
if strings.Contains(line, "func main() {") || strings.Contains(line, "func main(){") {// Here i loop trought all file lines
lines[i] = `func main() {
fmt.Println("new line")`//here i replace the line with the new data
}
}
output := strings.Join(lines, "\n")// here i join and add the new lines
err = ioutil.WriteFile("file.go", []byte(output), 0644) // here i write to file with new data
if err != nil {
log.Fatalln(err)
}
}