Closed ddkwork closed 6 months ago
package main import ( "fmt" "go/ast" "go/parser" "go/printer" "go/token" "os" ) func main() { src := ` package main import "fmt" func main() { fmt.Println("Hello, World!") } ` fset := token.NewFileSet() node, err := parser.ParseFile(fset, "", src, parser.ParseComments) if err != nil { fmt.Println(err) return } newImport := &ast.GenDecl{ Tok: token.IMPORT, Specs: []ast.Spec{ &ast.ImportSpec{ Path: &ast.BasicLit{ Kind: token.STRING, Value: `"time"`, }, }, }, } node.Decls = append([]ast.Decl{newImport}, node.Decls...) printer.Fprint(os.Stdout, fset, node) }