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

9
我正在编写输出其他Go代码的Go代码。
我想知道是否有一种方法可以在完成编写的代码中调用gofmt工具来格式化代码。
我找到的关于gofmt的文档,例如官方文档,都是关于如何从命令行使用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
}

非常感谢您的时间和智慧。

1个回答

18

go/format包提供了一个可用于格式化任意文本的函数:

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

使用起来应该非常简单:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接