【发布时间】:2018-02-27 15:21:47
【问题描述】:
我无法理解以下代码的问题所在。 Visual Studio Code 编译器出现如下错误,因为包“util”未定义。
'Error' message: 'undefined: util.GetPortAndURL
我将以下内容放在 util.go 文件的顶部
package util
我还将 myproj/util 包导入到我的 handlers.go 文件中,该文件在其 init 方法中调用以下代码。
file, err := ioutil.ReadFile("./creds.json")
if err != nil {
fmt.Printf("File error: %v\n", err)
// use a better error pattern here
}
json.Unmarshal(file, &oathCred)
port, url := util.GetPortAndURL() <-------- Here
if (port != nil) && (url != nil) {
oathConf = &oauth2.Config{
ClientID: oathCred.ClientID,
ClientSecret: oathCred.ClientSecret,
RedirectURL: url + ":" + string(port) + "/auth",
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email", // You have to select your own scope from here -> https://developers.google.com/identity/protocols/googlescopes#google_sign-in
},
Endpoint: google.Endpoint,
}
}
getPortAndURL()函数在util.go中,如下
// GetPortandURL returns the URL and Port currently used
/*
'
This function should be used to set the port and url for the program until a
set function is created.
'
*/
func GetPortandURL() (int, string) {
port := 8080
url := "http://127.0.0.1"
return port, url
}
我的 GOPATH 是 C:\Users\Me\Documents\code\go
文件结构如下
go/src/
└── myproj
├── handlers
├── main
└── util
【问题讨论】:
-
将完整的错误粘贴到问题中。还有你的 GOPATH 中 myproj 文件夹的位置
-
表示 GetPortAndURL 未定义。你定义了吗?
-
是的,我已经将它定义为 util.go 中的一个函数。我也编辑了我的问题以反映该方法。
-
如果此处的代码与您的项目中的代码相同,则问题是该函数在包 util 中被称为
GetPortandURL,但您正在调用函数GetPortAndURL,其大写为A。跨度> -
@TylerCheek 您在问题中提出的错误是正确的。它没有说'package util'是未定义的,它说'undefined:util.GetPortAndURL'是包
GetPortAndURL中的函数util。否则将不清楚它指的是哪个函数,因为 2 个包可以有一个同名的函数。