记录一个编译go1.14老项目的问题

304 阅读3分钟

背景

最近 (2023年8月) 接手了一个go的老项目,该项目使用 grpc 和 etcd, 所以编译起来有版本问题,下面会根据报错提示,记录一下解决过程。

1. 安装 go

这里直接去官网: go.dev 下载安装最新的go包, 最终本人安装的是: go version go1.20.6 linux/amd64

2. 尝试build

首先用go mod tidy 命令来更新依赖, 之后尝试build, 由于有Makefile,打开Makefile看build过程,首先需要把proto文件编译成go语言包,然后才是 build

由于没有安装protoc , 首先去安装

3. 安装protoc

去官网 grpc.io/docs/langua… 根据提示来安装:

3.1 安装protoc

3.2 安装protoc 的go插件

go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2

安装成功后,就会在 $(go env GOPATH)/bin 目录下多两个可执行文件

配置环境变量:

export PATH="$PATH:$(go env GOPATH)/bin"

4. 再次编译构建

编译结果:

--go_out: protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate gRPC

See https://grpc.io/docs/languages/go/quickstart/#regenerate-grpc-code for more information.

这里的提示是, protoc-gen-go 使用的插件不对,要用 --go-grpc_out 来,但是这里的问题是,之前项目编译的好好的,由于编译器版本问题导致过不去, 这里就有两种解决方案了, 1. 是把编译脚本全改成新版的,要看工作量多少。 2.就是把编译降回去。

由于先保证编译过,再修改版本,本人选择第2种,先把编译软件版本降回去。

5. 降低编译插件的版本

这里无非使用到了两个变异插件:

  • protoc-gen-go 把proto文件生成go语言用的
  • protoc-gen-go 把proto文件生成go版本的 grpc实现

我们去项目里,找到原始 go.mod ,看这俩使用的版本:

由于之前我们使用了 go mod tidy, 会自动升级依赖,需要先用 git reset --hard 来恢复如初.

找到对应的protobuf : github.com/golang/protobuf v1.3.1

我们就去github看这个版本的用法:

golang/protobuf: Go support for Google's protocol buffers (github.com)

This module (github.com/golang/protobuf) contains Go bindings for protocol buffers.

It has been superseded by the google.golang.org/protobuf module, which contains an updated and simplified API, support for protobuf reflection, and many other improvements. We recommend that new code use the google.golang.org/protobuf module.

Versions v1.4 and later of github.com/golang/protobuf are implemented in terms of google.golang.org/protobuf. Programs which use both modules must use at least version v1.4 of this one.

See the developer guide for protocol buffers in Go for a general guide for how to get started using protobufs in Go.

See release note documentation for more information about individual releases of this project.

See documentation for the next major revision for more information about the purpose, usage, and history of this project.

以上说的就是,这个protobuf 模块包含了go绑定的 protocol buffers. 已经被 google.golang.org/protobuf 模块取代了,它使用了更简单的API, 和其他一些更新。我们建议新代码直接使用 google.golang.org/protobuf.

v1.4版本和之后的版本都用google.golang.org/protobuf来实现了,两者都用的话最低版本是 v1.4.

使用protobuf v1.3.1

我们系统里使用了 v1.3.1 ,很明显是和 google.golang.org/protobuf有冲突的,所以要把这俩降下去。

下载下来对应的版本, 然后构建

继续构建

然后构建项目, 构建成功