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

huangapple go评论88阅读模式
英文:

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

问题

我正在编写输出其他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)
    // 在这里插入调用gofmt自动格式化myFile.go的代码
}

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

英文:

I'm writing Go code that outputs other Go code.

I'd like to know if there's a way to call the gofmt tool to format the code I've written from within the code that's done the writing.

The documentation I've found on gofmt, e.g. the official docs, all deals with how to use gofmt from the command line, but I'd like to call it from within Go code itself.

Example:

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
}

Thanks in advance for your time and wisdom.

答案1

得分: 18

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

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

使用方法很简单:

content, err := format.Source(content)
// 检查错误
file.Write(content)
英文:

The go/format package makes a function available to format arbitrary text:

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

Should be as simple as:

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

huangapple
  • 本文由 发表于 2017年8月10日 22:30:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/45616552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定