0

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)
}
user2133814
  • 2,431
  • 1
  • 24
  • 34

1 Answers1

4

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242