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 :
Advertisement
Something interesting
Tutorials
+4.4k Golang : Valued expressions and functions example
+7.5k Golang : Handling Yes No Quit query input
+13.7k Golang : Image to ASCII art example
+87.8k Golang : How to convert character to ASCII and back
+35.5k Golang : Smarter Error Handling with strings.Contains()
+32.1k Golang : Validate email address with regular expression
+6.7k Golang : Check if password length meet the requirement
+20.7k Golang : Read directory content with os.Open
+27.7k PHP : Count number of JSON items/objects
+4k Detect if Google Analytics and Developer Media are loaded properly or not
+19.5k Golang : How to Set or Add Header http.ResponseWriter?