简体   繁体   中英

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

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, eg 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM