编写一个Go程序,既可以作为可执行文件运行,也可以作为模块使用。

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

Writing a Go program that acts as an executable as well as a module

问题

我目前正在尝试在Go中迈出第一步。现在我已经将一个我曾经用Node.js编写的工具移植过来,我对这个过程的简单性以及代码的整洁和简洁感到惊讶。

无论如何,我有一个问题,我自己到目前为止还没有解决:在Node.js中,可以在package.json文件中添加main入口和bin入口。这基本上意味着当使用以下命令安装时,可以创建一个作为可执行文件运行的模块:

$ npm install -g <module>

但是当使用以下命令安装时,它作为库运行:

$ npm install <module>

这里的技巧是,第一个命令使用bin入口,该入口内部使用模块的lib文件夹中的文件,而第二个版本直接指向这个lib文件。

所以...现在我想在Go中实现相同的行为:我想编写一个可以直接作为可执行文件运行的包,但同时也可以作为库导入到另一个应用程序中。我该如何做到这一点?

显然,我不能在一个.go文件中放置两个package调用。有什么提示吗?

英文:

I am currently trying to do my first steps in Go. Now I've ported a tool that I once written in Node.js, and I was surprised how easy that was, and how clean and concise the code is.

Anyway, I've got a question that I was not able to figure out by myself so far: In Node.js it's possible to add the main entry as well as the bin entry to the package.json file. This basically means that you can create a module that works as a executable when installed using

$ npm install -g &lt;module&gt;

but as a library when installed using

$ npm install &lt;module&gt;

The trick here is that the first one uses the bin entry, which then internally uses a file from the module's lib folder, but the second version directly points to this lib file.

So ... now I would like to have the same behavior in Go: I would like to write a package that you can directly run as an executable, but that as well you can import into another application as a library. How would I do that?

Obviously I can't put two calls to package into a .go file. Any hints?

答案1

得分: 1

以下是您要翻译的内容:

关于下面博客文章中的解决方案,您有什么看法?http://dan.munckton.co.uk/blog/2013/06/21/go-lang-packaging-creating-a-library-that-bundles-an-executable/

英文:

What about the solution in the following blog post? http://dan.munckton.co.uk/blog/2013/06/21/go-lang-packaging-creating-a-library-that-bundles-an-executable/

huangapple
  • 本文由 发表于 2014年11月21日 06:29:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/27050835.html
匿名

发表评论

匿名网友

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

确定