I'm currently discovering Golang and I'm currently playing with Mux and Gorm to try to build an API.
So everything is fine until the point where I have too much content in my main.go file so I want to split this API into multiple files,
Naturally, like I would do in a Node.js API, I create a models Folder, and a routes folder, and begin to put my Models in individual files in the models folder (model1.go, model2.go etc) to have a structure like:
/MyProject |main.go |/models |model1.go |model2.go
Then I google a bit (well, a lot now..) to know how to include them in my main.go file, and now i'm facing the fact that in Golang the design of the language wants that any external file is a package which may be used by any other golang app, which is not what I'm looking for, I just want to split the content of my project to have a better maintainability but it seems to be impossible with that project design in mind. I heard about vendoring since 1.6 but that's still not a solution cause that's make necessary to keep the dependencies and the project files at the same place, which is not a conventional (and logical) way to structure a project
I guess heavy and complex Golang projects don't have their entire code base into one single file so I'm just looking for the good way to structure a project into multiple files like they would do to maintain their projects.
/MyProject
|main.go
|model1.go
|model2.go
If you want to keep your code in one package only.
Different Approaches
One package When needed we can put variables in the package scope
Two packages We will import the code from the second package when needed
Three+ packages with package for config variables We will import the code from the config package when needed. The config package will hold variables like DB and TPL.
FYI: there is no global scope in Go. You can read more about it at Alex Edwards Code Organization Article