Golang go/format.Source() function examples

package go/format

Source formats src(1st parameter) in canonical gofmt style and returns the result or an (I/O or syntax) error. src is expected to be a syntactically correct Go source file, or a list of Go declarations or statements.

If src is a partial source file, the leading and trailing space of src is applied to the result (such that it has the same leading and trailing space as src), and the result is indented by the same amount as the first line of src containing code. Imports are not sorted for partial source files.

Golang go/format.Source() function usage examples

Example 1:

 embedSourceUnformated := bytes.NewBuffer(make([]byte, 0))
 ...
 // format the source code
 embedSource, err := format.Source(embedSourceUnformated.Bytes())
 if err != nil {
 fmt.Printf("error formatting embedSource: %s\n", err)
 os.Exit(1)
 }

Example 2:

 func generateCode(s structInfo) {
  name := s.Name
  fs := s.Fields
  var buf bytes.Buffer
  err := encodeTpl.Execute(&buf, map[string]interface{}{"TypeName": name, "Fields": fs})
  if err != nil {
 panic(err)
  }
  bs := regexp.MustCompile(`(\s*\n)+`).ReplaceAll(buf.Bytes(), []byte("\n"))
  bs = bytes.Replace(bs, []byte("//+n"), []byte("\n"), -1)
  bs, err = format.Source(bs)
  if err != nil {
 panic(err)
  }
  fmt.Println(string(bs))
 }

References :

https://github.com/calmh/xdr/blob/master/cmd/genxdr/main.go

http://golang.org/pkg/go/format/#Source

Advertisement