gpt4 book ai didi

戈朗。替换不是真正的 go 包的模块路径

转载 作者:行者123 更新时间:2023-12-02 18:30:25 37 4
gpt4 key购买 nike

有这个包https://github.com/open-telemetry/opentelemetry-proto其中仅包含 protobuf 定义。要生成 golang 代码,必须输入:

make gen-go

并且 go build 失败并显示以下消息:

build opentel: cannot load github.com/open-telemetry/opentelemetry-proto/gen/go/common/v1: module github.com/open-telemetry/opentelemetry-proto@latest found (v0.11.0), but does not contain package github.com/open-telemetry/opentelemetry-proto/gen/go/common/v

我尝试将 go.mod 文件中的一个路径替换为另一个路径,但显然我不太擅长。我怎样才能让它发挥作用?

我已将这些生成的文件复制到

$GOPATH/src/opentelemetry-proto/gen/go

我应该在主包内的导入语句中放入什么?

最佳答案

Go 源代码的生成方式存在一些挑战。我认为存储库作者的目标是跨语言以及 Go 的 GOPATH 和 GO MODULES 用例保持一致......所以,是的,对他们和我们来说都是粗糙的.

这是一个(!?)解决方案:

假设您位于 /path/to/somedir 中,并且它包含同一级别的 opentelemetry-proto 和“my-module”的克隆,即:

.
├── my-module
└── opentelemetry-proto
  1. make gen-go 像以前一样。这应该创建 ./opentelemetry-proto/gen

  2. ./opentelemetry-proto/gen/go/github.com/open-telemetry/opentelemetry-proto中转到go mod init github.com/open-telemetry/opentelemetry-proto:

.
├── gen
└── go.mod
  • my-module 中,go mod init my-module 然后:
  • go.mod:

    module my-module

    go 1.17

    require (
    github.com/open-telemetry/opentelemetry-proto v0.11.0
    )

    replace (
    github.com/open-telemetry/opentelemetry-proto => ../opentelemetry-proto/gen/go/github.com/open-telemetry/opentelemetry-proto

    NOTE With GOPATH paths down to packages are required (they're not using Go Modules) and so, if we were using GOPATH, we could GOPATH=${GOPATH}:${PROTO_GEN_GO_DIR}/github.com/open-telemetry/opentelemetry-proto

    然后,例如

    main.go:

    package main

    import (
    v1 "github.com/open-telemetry/opentelemetry-proto/gen/go/collector/metrics/v1"
    )

    func main() {
    // E.g.
    _ = v1.ExportMetricsServiceRequest{}
    }

    说明:

    make gen-go 不会创建模块,但我们可以创建一个。

    该模块是从 gen/go 下的路径隐含的,即 github.com/open-telemetry/opentelemetry-proto

    然后,在我们的项目中,我们可以replace来提供它的本地路径。该路径是克隆的路径,然后返回到我们新创建的 go.mod

    导入路径是模块(即过于复杂的替换路径)到我们感兴趣的包的路径。

    NOTE Commonly protobuf imports are pb but I've used v1.

    我会做什么:

    我认为生成代码的模块应该与其存储库相匹配。如果 opentelemetry-proto 是我的,我会在不使用 gen/go

    的情况下将源代码生成到存储库根目录中

    因为这将 - IMO - 简化一切:

    github.com/open-telemetry/opentelemetry-proto => ../opentelemetry-proto

    还有:

    import (
    v1 "github.com/open-telemetry/opentelemetry-proto/collector/metrics/v1"
    )

    关于戈朗。替换不是真正的 go 包的模块路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69517065/

    37 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com