如何在golang中隔离模块?

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

How to isolate modules in golang?

问题

我想知道是否可以使用Golang创建独立的模块,应用程序始终从一个文件开始,我可以根据条件分离多个REST模块并上传它们吗?

例如,我有一个包含REST和数据库的产品模块,还有一个包含REST和数据库的用户模块。我能否创建一种方式来动态选择是否只运行一个模块或同时运行两个模块?而不必将所有内容都导入到main.go文件中?

英文:

I would like to know if it is possible to create isolated modules with golang, the application always starts in a file, can i separate several REST modules and upload them depending on the conditions?

For example. I have a products module with Rest and database, and I have a users module with Rest and database. Can I create a way to choose if I will run only one or both dynamically? Without having to import everything into a main.go file?

答案1

得分: 1

Go是一种编译语言,import发生在构建时而不是运行时。每个模块源代码都会被导入并编译成最终的二进制文件,然后你运行的就是这个二进制文件。

要实现你所要求的,你可能需要将程序拆分为多个二进制文件,每个文件只包含与其职责相关的代码部分。然后你还需要提供一些通信机制(例如,拦截传入请求并在内部进行相关请求,比如用户服务或产品服务等)。这通常被称为微服务架构

对于较小的项目,我建议先将所有内容放在一起;随着项目的发展(如果有问题的话),可以逐渐重构为微服务。

英文:

Go is compiled language and import happens at the build time, not at the run time. Each module source is imported and compiled into the final binary and that's what you run then.

To achieve what you are asking for you'd probably need to split your program into multiple binaries each containing only relevant portion of code for its responsibility. Then you would need also to provide some communication between them (e.g. having gateway that intercepts incoming request and make relevant request(s) internally to e.g. Users service or Products service, etc.). This is often called microservice architecture.

For smaller project I recommend just put everything together first; and as it grows (and causes problems, if ever) eventually refactor to microservices.

huangapple
  • 本文由 发表于 2022年9月19日 01:22:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/73764928.html
匿名

发表评论

匿名网友

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

确定