我正在编写输出其他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
}
Run Code Online (Sandbox Code Playgroud)
提前感谢您的时间和智慧.
该go/format包使函数可用于格式化任意文本:
https://golang.org/pkg/go/format/
应该如此简单:
content, err := format.Source(content)
// check error
file.Write(content)
Run Code Online (Sandbox Code Playgroud)