Golang go/parser.ParseFile() function examples
package go/parser
ParseFile parses the source code of a single Go source file and returns the corresponding ast.File node. The source code may be provided via the filename of the source file, or via the src parameter.
If src != nil, ParseFile parses the source from src and the filename is only used when recording position information. The type of the argument for the src parameter must be string, []byte, or io.Reader. If src == nil, ParseFile parses the file specified by filename.
The mode parameter controls the amount of source text parsed and other optional parser functionality. Position information is recorded in the file set fset.
If the source couldn't be read, the returned AST is nil and the error indicates the specific failure. If the source was read but syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by file position.
Golang go/parser.ParseFile() function usage examples
Example 1:
var path string
fset := token.NewFileSet()
pkg, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
Example 2: (from http://golang.org/pkg/go/parser/#ParseFile )
package main
import (
"fmt"
"go/parser"
"go/token"
)
func main() {
fset := token.NewFileSet() // positions are relative to fset
// Parse the file containing this very example
// but stop after processing the imports.
f, err := parser.ParseFile(fset, "example_test.go", nil, parser.ImportsOnly)
if err != nil {
fmt.Println(err)
return
}
// Print the imports from the file's AST.
for _, s := range f.Imports {
fmt.Println(s.Path.Value)
}
}
References :
Advertisement
Something interesting
Tutorials
+8.4k Golang : Convert word to its plural form example
+20.2k Golang : How to get own program name during runtime ?
+8.6k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+11k How to test Facebook App on localhost ?
+21.8k Golang : Convert string slice to struct and access with reflect example
+5.9k Unix/Linux : How to open tar.gz file ?
+33.7k Golang : All update packages with go get command
+12.8k Golang : Convert int(year) to time.Time type
+12.5k Golang : HTTP response JSON encoded data
+13.6k Golang : Strings comparison
+25.3k Golang : Convert uint value to string type
+9.4k Golang : Web(Javascript) to server-side websocket example