go/format

Guided tour · Go Tooling · pkg.go.dev →

gofmt as a library. Format Go source bytes or an AST node back to canonical form.

Usage

Source (bytes)

out, err := format.Source([]byte("package p\nvar  x=1"))
// out == "package p\n\nvar x = 1\n"

Node (AST + FileSet)

var buf bytes.Buffer
format.Node(&buf, fset, file)
fmt.Println(buf.String())