main.go 514 B

1234567891011121314151617181920212223242526272829303132333435
  1. package main
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "go/parser"
  6. "go/token"
  7. )
  8. func main() {
  9. fset := token.NewFileSet() // positions are relative to fset
  10. const src = `package foo
  11. import (
  12. "fmt"
  13. "time"
  14. )
  15. func bar() {
  16. fmt.Println(time.Now())
  17. }`
  18. // Parse src but stop after processing the imports.
  19. f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly)
  20. if err != nil {
  21. fmt.Println(err)
  22. return
  23. }
  24. // Print the imports from the file's AST.
  25. for _, s := range f.Imports {
  26. fmt.Println(s.Path.Value)
  27. }
  28. }