gogenerategofmt

go generate stdout piped to gofmt to file


What is the syntax so go generate can pipe stdout from go run to gofmt and ultimately to a file? Below is simple example of what I have tried. Its in the file main.go. I can't find any examples of this after searching. Thank you.

Edit: ultimately I would like to use go generate and have it write a formatted file.

//go:generate go run main.go | go fmt > foo.go
package main

import "fmt"

const content = `
package main
func     foo() string {return "Foo"}
`

func main() {
    fmt.Print(content)
}

Solution

  • Use the format package directly instead of running a shell:

    //go:generate go run main.go
    package main
    
    import (
        "go/format"
        "io/ioutil"
        "log"
    )
    
    const content = `
    package main
    func     foo() string {return "Foo"}
    `
    
    func main() {
        formattedContent, err := format.Source([]byte(content))
        if err != nil {
            log.Fatal(err)
        }
        err = ioutil.WriteFile("foo.go", formattedContent, 0666)
        if err != nil {
            log.Fatal(err)
        }
    }
    

    Avoid using a shell like bash because the shell may not be available on all systems where the Go tools run.