Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parsing go file error: 3:1: expected 'package', found 'import' (and 1 more errors) #35959

Closed
lcwj3 opened this issue Dec 4, 2019 · 1 comment

Comments

@lcwj3
Copy link

lcwj3 commented Dec 4, 2019

What version of Go are you using (go version)?

$ go version
go version go1.13.3 linux/amd64

What did you do?

I was trying to use the go/parser to extract dependency from go files, and I followed this example example-ParseFile, here is my code:

package main

import "C"
import (
	"fmt"
	"go/parser"
	"go/token"
	"io/ioutil"
	"strings"
)

func Ioutil(name string) string{
	if contents,err := ioutil.ReadFile(name);err == nil {
		result := strings.Replace(string(contents),"\n","",1)
		return result
	}
	return ""
}
func main()  {
	fset := token.NewFileSet() // positions are relative to fset
	src := Ioutil("/home/lcwj3/go_repos/public/alfredemoji/main.go")
	strings.Replace(src, "`", "'",-1)
	// Parse src but stop after processing the imports.
	f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly)
	if err != nil {
		fmt.Println(err)
	}
	var imports []string
	for _, s := range f.Imports {
		imports = append(imports, s.Path.Value)
	}
	fmt.Println(imports)
	// Print the imports from the file's AST.
	return
}

And the test example's code is like

// Package gorequest inspired by Nodejs SuperAgent provides easy-way to write http client
package gorequest

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"reflect"
	"strings"
	"time"
)

Then this will return a error:'3:1: expected 'package', found 'import' (and 1 more errors)'

What did you expect to see?

An interesting thing is that if I put an empty line between the first line(comment) and second line(package gorequest), the error will disappear and the output is correct:
["bytes" "encoding/json" "errors" "io/ioutil" "net" "net/http" "net/url" "reflect" "strings" "time"]

@lcwj3
Copy link
Author

lcwj3 commented Dec 5, 2019

Sorry, it is an issue from this function func Ioutil(name string) string, which will remove the first '\n', I copied from other sources, sorry for disturbing.

@lcwj3 lcwj3 closed this as completed Dec 5, 2019
@golang golang locked and limited conversation to collaborators Dec 4, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants