Programmatic Formatting With go/format

format.Source reformats complete Go snippets with the same rules as gofmt and returns a parse error instead of panicking on broken syntax.

GoCli Tooling

Code

gosnippet
17 lines
package main

import (
	"fmt"
	"go/format"
)

func main() {
	messy := []byte("package main\nimport \"fmt\"\nfunc main(){fmt.Println(  \"hello\" )}")
	tidy, err := format.Source(messy)
	fmt.Println("err:", err)
	fmt.Println(string(tidy))

	// a syntax error returns an error and a nil result, no panic
	broken, err := format.Source([]byte("func broken-name() {"))
	fmt.Println("broken err:", err != nil, "output nil:", broken == nil)
}

How the snippet works

The snippet is organized around the function main.

Watch out for

  • The third-party count is zero; the runtime already has every API used here.

Putting it to use

Entry signature: func main()

Watch for labeled lines in the run — err:, broken err: — when the file runs.

The core lines of the flow

broken, err := format.Source([]byte("func broken-name() {"))
fmt.Println("broken err:", err != nil, "output nil:", broken == nil)
}

Interactive Tools for This Topic

FAQ

What does Programmatic Formatting With go/format print when run?
Running the file directly is enough — expect labeled output lines such as `err:`, `broken err:`.