2017-08-10 6 views
2

私は他のGoコードを出力するGoコードを書いています。書いたGoコードの中から書いたファイルを書式設定するためにgofmtを呼び出すことはできますか?

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 
} 

感謝。

答えて

5

go/formatパッケージには、任意のテキストの書式を設定するために利用可能な機能になります:

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

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

は同じくらい簡単であるべき

関連する問題