GopherSnippetsStar

Code snippets with tests and testable examples for the Go programming language

How to format Go code programmatically

Snippets Index - Run code on Go playground - Edit

// Code can be formatted programmatically in the same way like running go fmt,
// using the go/format package
package main

import (
	"fmt"
	"go/format"
	"log"
)

func Example() {
	unformatted := `
package main
       import "fmt"

func  main(   )  {
    x :=    12
fmt.Printf(   "%d",   x  )
	}


`
	formatted, err := format.Source([]byte(unformatted))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s", string(formatted))
	// Output:
	// package main
	//
	// import "fmt"
	//
	// func main() {
	//	x := 12
	//	fmt.Printf("%d", x)
	// }
}

by psampaz - source code - comment below or here