我试图导入本地模块,但我无法使用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。有关如何设置Go项目的信息,请参阅 https://github.com/golang/go/wiki/Modules ,尽管已在~/.bashrc文件中设置GO111MODULE=on,但请在VScode中发出警告。
发布于 2020-03-14 08:41:02
阅读:伊恩·兰斯·泰勒的评论 (围棋的核心团队)
我知道三种方法:
# 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 itself1. Turn off Go Modules `GO111MODULE=off`
2. Remove `go.mod` file
# 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之外不工作)
发布于 2021-05-29 14:11:45
以下是步骤-
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文件夹并行的文件夹
当您安装任何软件包时,它应该位于pkg文件夹中,并且在执行go mod整齐之后,应该生成一个文件。
发布于 2021-10-06 08:12:48
只有go mod tidy在根文件夹为我做的
https://stackoverflow.com/questions/60680470
复制相似问题