You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go 1.11 Ubuntu下GOPATH配置及Go包查找失败问题问询

在Ubuntu的Go 1.11中配置GOPATH并解决包找不到问题

我来帮你一步步解决这两个问题:

一、Ubuntu系统Go 1.11版本设置GOPATH环境变量

Go 1.11已经引入了Go Modules,但如果你还是需要使用传统的GOPATH模式,配置方法如下:

1. 选择要编辑的配置文件

根据生效范围选择:

  • 仅对当前用户生效:编辑~/.bashrc(Bash终端)或~/.zshrc(Zsh终端)
  • 对所有系统用户生效:编辑/etc/profile或/etc/bash.bashrc

2. 具体配置步骤

  • 打开终端,以编辑当前用户的Bash配置为例:
    nano ~/.bashrc
    
  • 在文件末尾添加以下内容(把/home/ubuntu/work换成你实际想要设置的GOPATH路径,从你的错误信息看当前系统识别的GOPATH是这个路径):
    export GOPATH=/home/ubuntu/work
    export PATH=$PATH:$GOPATH/bin
    
  • 保存并退出编辑器(nano中按Ctrl+O,回车确认,再按Ctrl+X退出)
  • 让配置立即生效:
    source ~/.bashrc
    
  • 验证配置是否成功:
    echo $GOPATH
    
    输出你设置的路径就说明配置好了。

二、解决go run main.go的包找不到错误

先看你遇到的错误信息:

main.go:10:2: cannot find package "github.hpe.com/hybridpoc/marketplace-terraform-tf-broker/broker/github" in any of:
/home/ubuntu/go/src/github.hpe.com/hybridpoc/marketplace-terraform-tf-broker/broker/github (from $GOROOT)
/home/ubuntu/work/src/github.hpe.com/hybridpoc/marketplace-terraform-tf-broker/broker/github (from $GOPATH)
main.go:11:2: cannot find package "github.hpe.com/hybridpoc/marketplace-terraform-tf-broker/handlers" in any of:
/home/ubuntu/go/src/github.hpe.com/hybridpoc/marketplace-terraform-tf-broker/handlers (from $GOROOT)
/home/ubuntu/work/src/github.hpe.com/hybridpoc/marketplace-terraform-tf-broker/handlers (from $GOPATH)

问题核心是你的代码存放路径和GOPATH的目录结构不匹配:
你的代码现在在~/.work/src/...,但Go会去$GOPATH/src目录下查找包,而你的GOPATH是/home/ubuntu/work,所以找不到对应包。

两种解决办法:

方法1:调整代码路径到GOPATH规范目录

把你的代码移动到$GOPATH/src下,执行命令:

mv ~/.work/src/github.hpe.com/hybridpoc/marketplace-terraform-tf-broker /home/ubuntu/work/src/github.hpe.com/hybridpoc/

然后进入代码目录执行:

cd /home/ubuntu/work/src/github.hpe.com/hybridpoc/marketplace-terraform-tf-broker
go run main.go

方法2:改用Go Modules(推荐,Go 1.11+原生支持)

如果你不想受GOPATH的目录约束,可以用Go Modules来管理依赖:

  • 进入你的代码目录:
    cd ~/.work/src/github.hpe.com/hybridpoc/marketplace-terraform-tf-broker
    
  • 初始化Go模块:
    go mod init github.hpe.com/hybridpoc/marketplace-terraform-tf-broker
    
  • 直接执行go run main.go,Go会自动处理依赖路径,不需要依赖GOPATH。

内容的提问来源于stack exchange,提问作者Sahana J C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:53:40