你能调用 gofmt 来格式化你从编写它的 Go 代码内部编写的文件吗?

Can you call gofmt to format a file you've written from inside the Go code that wrote it?

我正在编写输出其他 Go 代码的 Go 代码。

我想知道是否有一种方法可以调用 gofmt 工具来从完成编写的代码中格式化我编写的代码。

我在 gofmt 上找到的文档,例如the official docs,所有内容都涉及如何从命令行使用 gofmt,但我想从 Go 代码本身调用它。

示例:

func WriteToFile(content string) {
    file, err := os.Create("../output/myFile.go")
    if err != nil {
        log.Fatal("Cannot create file", err)
    }
    defer file.Close()
    fmt.Fprint(file, content)
    //Insert code to call gofmt to automatically format myFile.go here
}

提前感谢您的时间和智慧。

go/format 包提供了一个函数来格式化任意文本:

https://golang.org/pkg/go/format/

应该很简单:

content, err := format.Source(content)
// check error
file.Write(content)