简体   繁体   中英

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)
}

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.

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