好的,所以这个问题之前已被问过,我相信我已经查看了所有这些问题并测试了答案,但我将解释每个问题与我的情况不符。我可能在其中一个中错过了答案,但我读了每一个,并试图看看它是否适合我的情况
How to import local packages in go?我相信我的导入遵循答案的结构
Go build: "Cannot find package" (even though GOPATH is set)我不确定这个是否完全相关,但我认为这不是同样的错误。
Golang - Why can't I import local package in GOPATH/src/project but can in home directory?我的导入路径不是相对的,所以这个问题并不相关。
我的错误很简单:
cannot find package "api/handlers" in any of:
C:\Go\src\api\handlers (from $GOROOT)
C:\Projects\Go\src\api\handlers (from $GOPATH)`
我的项目结构如下:
src
|
--api
|
-- index.go
-- repo.go
|
github.com
|
main.go
环境变量:
$GOPATH : C:\Projects\Go
$GOROOT : C:\Go\
index和repo.go都有相同的包名,导入,只是一个空函数:
package handlers
import (
"net/http"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
}
我的主要内容:
package main
import (
"fmt"
"log"
"net/http"
"api/handlers"
)
func main() {
http.HandleFunc("/api/index", handlers.indexHandler)
http.HandleFunc("/api/repo", handlers.repoHandler)
log.Fatal(http.ListenAndServer("localhost:8080", nil))
}
答案 0 :(得分:1)
正在发生的事情是import api/handlers
正在文件夹handlers
中查找文件夹api
,然后在内容中查找包名称。在handlers
中添加api
文件夹,然后将index.go
和repo.go
移到该文件夹中。或者只需将包名称更改为这些文件中的api
,然后执行import api
。
关于您的评论:
不能引用未导出的名称handlers.indexHandler
为了能够使用主程序包中的函数indexHandler
,您应该将其重命名为IndexHandler
。在go中,对于其他包可以访问的东西,名称需要以大写字母开头。