go - 如何在导入包时在 GOPATH 中搜索包?

标签 go import gopath

package main

import (
    "fmt"
    "controller/userhandler"   //not able to import this custom package      
    "github.com/gin-gonic/gin"                                         
    "net/http"                                                         
    "github.com/jinzhu/gorm"                                               
  _ "github.com/jinzhu/gorm/dialects/postgres"
)

func main(){
}

下面的代码显示 Go 只在 GOROOT 中搜索包。在 GOROOT 中找不到 controller/userhandler 之后,理想情况下,它应该在 GOPATH 中查找包,但它没有。

我已经将 GOPATH 设置为我的工作区路径,其中包括文件夹:binsrcpkg.

$ go build main.go                                                           
main.go:5:2: package controller/userhandler is not in GOROOT (/usr/local/go/src/controller/userhandler)

最佳答案

运行 go mod init MODULE_NAME(如果项目在 GOROOTGOPATH 之外)或者只是简单地 go mod init(如果项目在 GOROOT 或 GOPATH 中)。该命令应在项目的根文件夹上运行。这将创建一个 go.mod 文件,使 go 能够解析您的包。

关于go - 如何在导入包时在 GOPATH 中搜索包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62760999/

相关文章:

windows - 如何将 uintptr 转换为 go struct

go - strings.Split() 似乎在 [] 处逃脱并继续前进(没有错误)

python - 从模块运行测试

macos - GOPATH 没有被自动设置?

go - 在Go工作区中安装Gota软件包

networking - GoLang 监听端口范围

go - 在 C 共享库中公开一个带有 2D slice 作为参数的函数(通过 JNA 和 C 在 Java 中使用)

.net - 导入定宽文件到oracle

Python错误: cannot import name cross_validation

go - 使用go.mod在目录中将软件包安装到GOPATH