Popular Web Libraries
As our application gets larger and more complex, we need help from some open source libraries to make our life easier. There are many good web frameworks out there but I am going to show you the couple popular libraries I've enjoyed using.
Echo is a minimalist web framework. I am using it primarily for routing and HTTP request/response handling. The setup is very easy; I create a server and then configure handlers for it.
Each handler looks like the following.
Logging is crucial for debugging applications in production. Go provides a default log
package. However, sometimes you'd want more. logrus
provides colorful logging and additional log fields to identify the source of errors. More importantly, logrus
provides integration with Sentry.
Command-line Interface (CLI)
So far we've been building applications that runs a single command, i.e. whatever you put in your main function. What if we want to have more command like the following.
We can accomplish that using the cobra
package. We define a list of commands and each command is mapping to an execution function, much like main()
.
In our main function, we just need to run the Execute
function on the root command.
Every modern day application needs an ORM. Every major framework provides it, e.g. Django & Rails. However, I personally advise against using ORM, unless time is a limiting resource to you, which is the case here. Currently gorm
is the most popular ORM for Golang, at least according to GitHub stars.
gorm
is still lacking in features compared to ActiveRecord, but for most cases it is good enough. If performance is an issue, try to write your own raw SQL query. gorm
provides the following key benefits.
Associations
Eager Loading
Hooks
Transactions
SQL Builder
Auto Migrations
Here's a simple example on how to use gorm
. More detailed usage will be discussed in the user authentication project.
Although gorm
provides auto migration, I still prefer writing the migrations manually so that I can up or down migrate to any version I want. Sometimes you gotta appreciate raw SQL a bit. SQL itself is a domain specific language and fairly human readable.
Running migration is pretty easy with golang-migrate/migrate
. First, you need to create your SQL files, e.g.
Put all the files into a migrations directory and then run migration in Go.
Last updated