Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

gofmt

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.

like image 984
R. Duke Avatar asked Aug 10 '17 14:08

R. Duke


People also ask

How do I use Goimport?

goimports If your project does not have goimports, click the go get goimports link in the Goimports file notification window. Otherwise, open the Terminal tool window (View | Tool Windows | Terminal), and type the following command to install goimports: go get golang.org/x/tools/cmd/goimports . Press Enter .

Which GO command is used to format the Go source code?

Gofmt is a tool that automatically formats Go source code.

How does go FMT work?

Without an explicit path, it processes the standard input. Given a file, it operates on that file; given a directory, it operates on all .go files in that directory, recursively. (Files starting with a period are ignored.) By default, gofmt prints the reformatted sources to standard output.

How do I format a go file?

We can use the gofmt command in the CLI to autoformat a Golang source file. We can autoformat the go code with gofmt package in Golang. Using the command gofmt command from the terminal or command line, we can format the go source file.


1 Answers

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)
like image 107
captncraig Avatar answered Oct 01 '22 00:10

captncraig