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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.