I have a large Go program that is spread across 50+ miscellaneous Go files in the root of my package folder. I know that this is considered terrible, so I've decided to embark upon splitting up the program into some subpackages for better organization.
Unfortunately, after splitting off the logical parts of my programs into subpackages, I'm running into the dreaded "import cycle not allowed" error. This is because the Go compiler refuses to compile anything with circular imports. But the different logical parts of my program need to communicate with each other...
I've done some research online and found some excellent resources, like this excellent StackOverflow question that attempts to explain what to think about to solve this problem at a high level.
My apologies, but this post is way over my head, and I was wondering if someone could spell out an exact solution for my specific code situation, and hopefully in simpler language aimed at a complete beginner to Go.
A brief description of how my code is organized and what it does:
- It connects to 3 different servers using 3 different protocols (Twitch.tv, Discord, and a custom WebSocket server).
- It seems obvious to make 3 subpackages, one for each server type, and then initialize all of them in a
main.go
file. - Each subpackage is not just an interface; it contains a collection of global variables (that track the connection + other things) and a bunch of functions. (Note that I can refactor this such that its all contained within one giant interface, if necessary.)
- 95% of the time, the subpackages receive messages from their individual servers and send messages back to their individual servers, so the subpackages are mostly compartmentalized.
- However, sometimes the Twitch.tv module needs to send a message to the Discord server, and the Discord server needs to send a message to the Twitch.tv server. So the Discord server needs to be able to call the "Send()" functions inside the Twitch.tv subpackage, and the Twitch.tv subpackage needs to be able to call the "Send()" function of the Discord subpackage! So this is where my circular problem comes from.