如何导入一个包含 git 子模块依赖的 golang 包?

huangapple go评论151阅读模式
英文:

How to Import a golang package which has git submodule depedency in it

问题

我想创建一个包含JSON文件的存储库,比如将国家映射到国家ID,然后在一个名为transformer的Golang包中使用git子模块导入这个存储库。transformer包会读取国家的JSON文件并创建一个映射表,然后在一些操作中使用该映射表。

示例结构如下:

repoA:
-- country.json(国家文本到国家ID的映射)

repoB:(Golang包)
-- json(使用git子模块添加的repoA)
-- transformer.go(读取json/country.json文件并创建查找表的逻辑)。

repoC:(Golang服务)
-- main.go(使用repoB的transformer功能)。

当我们导入创建的包(transformer或repoB)时,它依赖于包含我们要读取的国家JSON文件的repoA,但在repoC中没有导入该依赖项,因此repoB包无法读取JSON。

尝试获取子模块,尝试创建构建和运行,但无法读取JSON文件。

期望导入的包中存在子模块依赖项。

英文:

I want to create a repo containing json files let us say mapping of countries to country ids, and import this repo in a golang package using git submodule for example called as transformer which reads the json for countries and creates a map and uses that for some operations.

sample structure

repoA: 
-- country.json (mapping of country text to country id)

repoB: (golang package)
-- json (repoA added using git submodule)
-- transformer.go (logic to read json/country.json file and create lookup tables ).

repoC: (golang service)
-- main.go (uses repoB's transformer functionality).

When we import the created package (transformer or repoB), its dependency which is on repoA containing our country json file to read, is not imported in repoC and hence repoB package fails to read json.

tried to fetch submodules,
tried to create build and run but json file was not being read.

expecting that the submodule dependency is present in the imported package.

答案1

得分: 1

一种解决方法是在repoB中添加一个生成器,用于生成一个包含json文件内容的go源文件。例如,

// jsondata.go
// 由工具生成的代码;请勿编辑。

package jsondata

const file1 = `{"field":"value".....`
const file2 = `{"field":"value".....`

如果文件太大,可以将它们压缩。记得将这个文件放在一个单独的包中,这样当这个包没有被导入时,它不会影响最终程序的大小。

这就是go工具本身设计的嵌入tzdata到程序中的方式。有关更多信息,请参阅这个提案:time: add time/tzdata package and timetzdata tag to embed tzdata in program

英文:

One workaround is to add a generator in repoB to generate a go source file that holds the content of the json files. For example,

// jsondata.go
// Code generated by tool; DO NOT EDIT.

package jsondata

const file1 = `{"field":"value".....`
const file2 = `{"field":"value".....`

If the files are too large, you can zip them. Remember to put this file into a separate package so when this package is not imported, it won't affect the size of the final program.

This is how the go tool itself is designed to embed tzdata in a program. See this proposal for more information: time: add time/tzdata package and timetzdata tag to embed tzdata in program

huangapple
  • 本文由 发表于 2023年4月13日 16:02:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定