我正在尝试导入本地模块,但是无法使用go mod
导入它。我最初使用go mod int github.com/AP/Ch2-GOMS
请注意,我的环境是go1.14
,并且我使用VSCode作为编辑器。
这是我的文件夹结构
Ch2-GOMS
│ ├── go.mod
│ ├── handlers
│ │ └── hello.go
│ └── main.go
我的main.go
代码:
package main
import (
"log"
"net/http"
"os"
"github.com/AP/Ch2-GOMS/handlers" // This gives "could not import github.com/AP/Ch2-GOMS/handlers" lint error
)
func main() {
l := log.New(os.Stdout, "product-api", log.LstdFlags)
hh := handlers.NewHello(l)
sm := http.NewServeMux()
sm.Handle("/", hh)
http.ListenAndServe(":9090", nil)
}
我看不到本地模块(例如handlers.NewHello
)的自动完成。
go build
生成了go.mod
的内容:
module github.com/AP/Ch2-GOMS
go 1.14
我也得到 您既不在模块中也不在您的GOPATH中。请参阅https://github.com/golang/go/wiki/Modules,以获取有关如何设置Go项目的信息。即使我在GO111MODULE=on
文件中设置了~/.bashrc
,也可以在VScode中使用警告 >
答案 0 :(得分:1)
阅读:Ian Lance Taylor的comment(Go的核心团队)
我知道三种方式:
# Inside
# Ch2-GOMS
# │ ├── go.mod
# │ ├── handlers
# │ │ └── hello.go
# │ └── main.go
# In Ch2-GOMS
go mod init github.com/AP/Ch2-GOMS
# In main.go
# Add import "github.com/AP/Ch2-GOMS/handlers"
# But, make sure:
# handlers/hello.go has a package name "package handlers"
您一定在做错事,这就是为什么它不起作用。
# Inside
# Ch2-GOMS
# │ ├── go.mod
# │ ├── handlers
# │ │ └── hello.go
# │ └── main.go
# Inside the handlers package
cd Ch2-GOMS/handlers
go mod init github.com/AP/Ch2-GOMS/handlers # Generates go.mod
go build # Updates go.mod and go.sum
# Change directory to top-level (Ch2-GOMS)
cd ..
go mod init github.com/AP/Ch2-GOMS # Skip if already done
go build # Must fail for github.com/AP/Ch2-GOMS/handlers
vi go.mod
在Ch2-GOMS / go.mod内并添加以下行:
# Open go.mod for editing and add the below line at the bottom (Not inside require)
replace github.com/AP/Ch2-GOMS/handlers => ./handlers
# replace asks to replace the mentioned package with the path that you mentioned
# so it won't further look packages elsewhere and would look inside that's handlers package located there itself
方法3 (对不耐烦的人非常快捷的黑客方式):
GO111MODULE=off
go.mod
文件# Check: echo $GOPATH
# If $GOPATH is set
mkdir -p $GOPATH/src/github.com/AP/Ch2-GOMS
cd $GOPATH/src/github.com/AP/Ch2-GOMS
# If $GOPATH is unset
mkdir -p ~/go/src/github.com/AP/Ch2-GOMS
cd ~/go/src/github.com/AP/Ch2-GOMS
# Now create a symbolic link
ln -s <full path to your package> handlers
原因:在构建过程中,编译器首先查找供应商,然后查找GOPATH,然后查找GOROOT。因此,由于有了符号链接,VSCode的go相关工具也将正确运行,这是因为它提供了依赖于GOPATH的符号链接(它们不能在GOPATH之外运行)
答案 1 :(得分:0)
以下是步骤-
on main folder - go mod init
2.go mod tidy
3.go to the folder where main file is present
4.install the package via
go get <package name>
5.go build
在上述步骤之前,您的项目路径应该是
project path = GOPATH/src/<project_name>
除了src文件夹
之外应该还有2个文件夹当你安装任何软件包时,它应该放在 pkg 文件夹中 并且在执行 go mod tidy 之后应该会生成一个文件