我已经使用协议缓冲和 gRPC 实现了一个 API 服务,然后使用 grpc-gateway 将其公开为一组 REST web 服务。
现在我到了需要维护不同版本的 API 的阶段,但是我陷入了困境。
例如,在我的 proto 文件中,我定义了这样一个处理程序。
当然,在我的Go代码中,我有一个函数
现在,假设我想要为
我的问题是,如何编写proto处理程序以为不同版本的端点提供服务?其中一个想法可能如下所示:
现在我到了需要维护不同版本的 API 的阶段,但是我陷入了困境。
例如,在我的 proto 文件中,我定义了这样一个处理程序。
rpc MerchantGet (MerchantRequest) returns (MerchantResponse) {
option (google.api.http) = {
get: "/v1.1.0/myapi/merchant/{MerchantID}"
};
}
当然,在我的Go代码中,我有一个函数
MerchantGet
,它映射到/v1.1.0/myapi/merchant/{MerchantID}
的GET
操作。现在,假设我想要为
MerchantGet
方法添加更多功能并发布一个新版本。我打算按照 语义化版本规范保持向后兼容性,因此如果我理解正确,这意味着我可以对我的MerchantGet
方法进行基础更改,并将其替换旧方法,只要它不需要第三方(MerchantRequest
)提供不同的输入或更改发送给第三方(MerchantResponse
)的响应,除非通过在响应末尾添加附加字段。(如果我在这个假设上错了,请纠正我)。我的问题是,如何编写proto处理程序以为不同版本的端点提供服务?其中一个想法可能如下所示:
rpc MerchantGet (MerchantRequest) returns (MerchantResponse) {
option (google.api.http) = {
get: "/v1.6.0/myapi/merchant/{MerchantID}"
additional_bindings {
get: "/v1.5.0/myapi/merchant/{MerchantID}"
}
additional_bindings {
get: "/v1.4.2/myapi/merchant/{MerchantID}"
}
additional_bindings {
get: "/v1.4.1/myapi/merchant/{MerchantID}"
}
additional_bindings {
get: "/v1.4.0/myapi/merchant/{MerchantID}"
}
additional_bindings {
get: "/v1.3.0/myapi/merchant/{MerchantID}"
}
additional_bindings {
get: "/v1.2.0/myapi/merchant/{MerchantID}"
}
additional_bindings {
get: "/v1.1.0/myapi/merchant/{MerchantID}"
}
};
}
但是这肯定不是实现这个的惯用方式吧?这绝对不够优雅,因为每次新的小版本或补丁发布时,我都需要将这些additional_bindings
扩展到我的每个方法中(上面只是举了一个例子)。