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

使用go.work的仓库执行go get为何抛出「包未在模块中使用」警告?

Go工作区依赖被标记为indirect,go mod tidy清理后报错的解决办法

问题场景

我要搭建一个多模块Go仓库,结构如下:

|- go.work
|- websocket
|  |- go.mod
|  |- go.sum
|  |- server.go
|- channel
|  |- main.go

websocket模块需要用到github.com/gorilla/websocket包,我在websocket目录执行了这些操作:

  1. go mod init github.com/kidfrom/learn-golang/websocket
  2. go get github.com/gorilla/websocket@v1.5.0
  3. go work use .

但现在碰到两个问题:

  • websocket/go.mod里弹出警告:github.com/gorilla/websocket is not used in this module
  • 一执行go mod tidy,这个依赖就被清掉,导致websocket/server.go报错:could not import github.com/gorilla/websocket (no required module provides package "github.com/gorilla/websocket")

相关文件内容

websocket/go.mod

module github.com/kidfrom/learn-golang/websocket

go 1.19

require github.com/gorilla/websocket v1.5.0 // indirect

websocket/go.sum

github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=

go.work

go 1.19

use (
    ./websocket
)

问题根源

依赖后面的// indirect注释是关键——这说明Go模块工具没检测到当前websocket模块的代码里直接导入了github.com/gorilla/websocket包。go mod tidy的逻辑就是移除模块里没被使用的依赖,所以这个标记为间接的依赖自然会被清掉。

解决步骤

  1. 检查server.go的导入语句
    打开websocket/server.go,确认里面确实导入了github.com/gorilla/websocket,比如:

    import "github.com/gorilla/websocket"
    

    要是你是从示例复制的代码,别漏了这个导入,也别不小心注释掉了。

  2. 在websocket目录重新执行依赖同步
    进入websocket文件夹,运行:

    go mod tidy
    

    这时候Go会扫描代码里的导入,自动把这个依赖从间接转为直接,go.mod里的// indirect会消失,以后再执行go mod tidy也不会清掉它了。

  3. 同步工作区依赖
    回到仓库根目录,执行:

    go work sync
    

    确保工作区里的各个模块依赖状态一致。

排查小技巧

要是你确定代码里已经导入了包,但Go还是没检测到,可以试试:

  • 清理模块缓存:go clean -modcache
  • 重新初始化模块(实在不行再用):先删了websocket里的go.mod和go.sum,再重新跑go mod init和go get

内容的提问来源于stack exchange,提问作者Jason Rich Darmawan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:20:57