I want to build an API based application using GO and MongoDB. I’m from Asp.net MVC background. Probably if I make an architecture with MVC web application things to be consider are
-
Separation of concerns(SoC)
- DataModel
- BusinessEntities
- BusinessServices
- Controllers
-
Dependeny Injection and Unity of Work
- Unit Testing
- MoQ or nUnit
- Integration with UI frameworks
- Angularjs or others
- RESTful urls that enables SEO
Below architecture could be a solution for my need in MVC based appications
There are resources around the web to build Asp.Net or Java based applications, but I have not find solution to Golang application architecture.
Yes GO is different to C# or Java, but still there are Structs, Interfaces to create reusable code and a generic application architecture.
Consider above points in mind, how we can make a clean and reusable project structure in GO applications and a generic repositories for DB(Mongodb) transactions. Any web resources also a great point to start.
5
Answers
I’ve also struggled about how to structure my Go web APIs in the past and don’t know any web resources that tell you exactly how to write a Go web API.
What I did was just check out other projects on Github and try out how they structured their code, for example, the Docker repo has very idomatic Go code on it’s API.
Also, Beego is a RESTful framework that generates the project structure for you in a MVC way and according to their docs, it can also be used for APIs.
I’ve been building a web APIs in golang for a little while now.
You’ll have to do some research but I can give you some starting points:
And for reference on how some things work together in the end:
Go Web API Repo — personal project
To my mind Go webapp project folder on production server can looks like on your picture just much simpler. Nothing special in assets structure – Static, Templates, Content, Styles, Img, JSlibs, DBscripts etc. usual folders. Nothing special in WebAPI – as usual you design which URI will respond required functionality and route requests to handlers accordingly. Some specifics – many gophers don’t believe in MVC architecture, it’s up to you surely. And you deploy one staticaly linked executable without dependencies. In your development environment you structure yours and imported/vendored sorce files in $GOPATH as in stdlib done but deploy only one executable in production environment, sure with static assets needed. You can see how to orginize Go source packages just in stdlib. Having just one executable what would you structure on production?
It depends on your own style and rules, in my company, we develop our projects this way:
company/envs/project.sh
file which has to be evaluated before service (outside the project in the image).zscripts
folder that contains all extra scripts, like adding users or publishing a post. Intended to be used only for debug proposes.project/models
./dogs
goes to packageproject/apps/dogs
and/cats
toproject/apps/cats
.project/manager
.project/static/[app/]
. Sometimes is required to have the optional[app/]
folder, but it only happens when two apps have dashboards or conflicting file names. Most of cases you won’t need to use[app/]
for static resources.Managers
We call a manager, a package that contains pure functions which helps apps to perform its task, for example, databases, cache, S3 storage, etc. We initialize each manager calling
package.Startup()
before we start to listen, and finalize callingpackage.Finalize()
when program is interrupted.An example of a manager could be
project/cache/cache.go
:in main.go (or your_thing_test.go):
And in a app (or module):
Modules
A module is a container of views and controllers that are isolated from other modules, using our configuration I would recommend to not create dependencies between modules. Modules are also called apps.
Each module configures its routes using a router, sub-router or what your framework provides, for example (file
project/apps/dogs/configure.go
):Then, all handlers live in
project/apps/dogs/handlers.go
:Finally you configure the app in main (or in a test):
Note: for views, you can add them to
project/apps/<name>/views
folder and configure them the using the same function.Other
Sometimes we also add a
project/constants
and aproject/utils
package.Here is what it looks like:
Note that in above sample,
templates
are separated from apps, thats because its a placeholder, directory is empty.Hope it was useful. Greetings from México :D.
1. Separation of concerns (SoC)
I haven’t worked with SoC directly, but I have my own pattern. You can adapt to whatever pattern (MVC, your own, etc.).
In my code, I separate my code into different packages:
Notes:
Setup()
function (with relevant arguments) that is called by the main package.apis
folder, they are often just to initialize external Go libraries. You also can directly import existing libraries into the handlers/models without anapis
package.I setup my mux as an exported global in the
handlers
package like this……and then create a file for each URL (different methods with the same URL are in the same file). In each file, I use Go’s
init()
function, which is ran after global variables are initialized (so it’s safe to use the router) but beforemain()
is ran (so it’s safe for main to assume everything has been setup). The great thing aboutinit()
is that you can have as many of those methods as you want in a single package, so they automatically get ran when the package is imported.Main then imports
myprojectname/handlers
and then serves thehandlers.Router
in main.2. Dependency Injection and Unity of Work
I haven’t worked with Unity of Work, so I have no idea of possible Go implementations.
For DI, I build an interface that both the real object and the mock objects will implement.
In the package, I add this to the root:
Then, the first line of each test I can change
DatabaseController
to whatever that test needs. When not testing, the unit tests should not be ran, and it defaults toDefaultController
.3. Unit Testing
Go provides a built in testing with the
go test package
command. You can usego test --cover
to also emit a coverage percent. You can even have coverage displayed in your browser, highlighting the parts that are/aren’t covered.I use the testify/assert package to help me with testing where the standard library falls short:
4. Integration with UI frameworks
I haven’t seen any for Angular. Although I haven’t used it, Go has a good template engine built into the standard lib.
5. RESTful URLs that enables SEO
Again, I can’t help you here. It’s up to you: send proper status codes (don’t send a 200 with a 404 page as you’ll get docked for duplicate pages), don’t duplicate pages (pay attention to
google.com/something
vsgoogle.com/something/
; hopefully your framework will not mess this up), don’t try to trick the search engine, and so on.