Go语言导入Meshtastic Protobuf SDK报错问题求助
修复Meshtastic Protobuf SDK导入失败问题
问题场景
我需要读取Meshtastic protobuf数据包,使用buf.build生成对应SDK并导入到mqtt.go文件:
package main import ( "encoding/json" "fmt" "io" "log" "os" "os/signal" "strings" "sync" "syscall" mqttProto "buf.build/gen/go/meshtastic/protobufs/protocolbuffers/go" mqtt "github.com/eclipse/paho.mqtt.golang" "google.golang.org/protobuf/proto" )
执行go run mqtt.go时触发错误:
no required module provides package buf.build/gen/go/meshtastic/protobufs/protocolbuffers/go; to add it: go get buf.build/gen/go/meshtastic/protobufs/protocolbuffers/go
执行go get buf.build/...后无输出,问题仍存在;执行go mod tidy时出现以下错误:
go: finding module for package buf.build/gen/go/meshtastic/protobufs/protocolbuffers/go go: router imports buf.build/gen/go/meshtastic/protobufs/protocolbuffers/go: module buf.build/gen/go/meshtastic/protobufs/protocolbuffers/go@latest found (v1.32.0-20240228025038-216ffc09a4e9.1), but does not contain package buf.build/gen/go/meshtastic/protobufs/protocolbuffers/go
尝试go clean -modcache也未解决问题。
解决方案
方案一:通过buf工具本地生成代码(推荐)
问题根源是buf.build的远程模块路径不匹配,本地生成代码可彻底避免路径问题:
- 初始化buf配置:在项目根目录执行
buf mod init - 添加Meshtastic依赖:创建
buf.yaml文件,写入以下内容:version: v1 name: buf.build/your-username/your-project-name deps: - buf.build/meshtastic/protobufs - 配置代码生成规则:创建
buf.gen.yaml文件,指定Go代码输出目录:version: v1 plugins: - name: go out: internal/meshtastic opt: paths=source_relative - 生成本地SDK代码:执行命令生成代码到指定目录
buf generate buf.build/meshtastic/protobufs - 修正导入路径:修改
mqtt.go中的导入语句,替换为本地生成的路径:// 替换成你的项目模块完整路径,比如"github.com/your-username/your-project/internal/meshtastic" mqttProto "./internal/meshtastic" - 整理依赖并运行:
go clean -modcache go mod tidy go run mqtt.go
方案二:直接使用官方Go模块
如果不想用buf工具,可直接使用Meshtastic官方维护的Go protobuf模块:
- 安装官方模块:
go get github.com/meshtastic/go-protobuf - 修正导入路径:修改
mqtt.go中的导入语句:mqttProto "github.com/meshtastic/go-protobuf/meshtastic" - 整理依赖并运行:
go mod tidy go run mqtt.go
内容的提问来源于stack exchange,提问作者Lorenzo Andreasi
相关产品推荐
相关产品推荐

