In a previous blogpost I wrote how to create a Webserver in Go with graceful shutdown. This time I want to show you a more improved version which you can utilize better in your projects as it can be used as a drop in server.go file in your project where I also make use of some popular high performing libraries.
In previous example I coded the full example in main.go. Although nothing wrong with that I learned while building microservices for a while it would be more convenient for me if I could copy my boilerplate more easy in the new project and keep my main.go more clean. As most of the microservices have different kind of bootstrap I use main.go now solely for bootstrapping different packages and components like the webserver.
We would be talking about a very plain main.go where I would just delegate all the work to other packages and files and solely use it to bootstap my application. See following as an example.
For new readers of my blog and readers new to Go, I would like to refer you to following blog post. In this blog I explain you how to setup a development environment for Go and how to initialize a Go project. For readers already known to Go please continue reading.
Now lets have a look on how I would implement my web server in a file named server.go, which I will be able to drop into any new project as a boilerplate. To mention first I would like to highlight you don't necesarely need any third party libraries for very simple webservers. However for convenience and development speed I took 2 external dependencies which are outstanding in benchmarks and have a good community supporting the library.
First of these libraries is chi which is a nice and very well performing library to build webservers and restful APIs. It ships with middelwares and allows you to easily build your own middleware. More on that further on where I will show you as well a zap.Logger middleware I created to use the zap.Logger for all requests in a chi middleware.
That brings us to the second library I included. The zap.Logger, created by Uber. It is a nice very high performant logger using different logging levels and different logger backends allowing you to do nicely structured logging. For example logging into Elasticsearch and Kibana.
At the end of this blog I included the urls to both the libraries as further reference.
So lets start by first implementing our NewServer func which returns our server struct.
As you can see we are creating a zap.Logger using the convenience factory func NewDevelopment. Zap does offer more complex and finegrained configuration of the logger, but in general I use this simple setup. Furthermore you see I'm calling a func newAPI(logger). This I use to bootstrap a chi.Mux that allows us to define the endpoints for our webserver. E.g. RESTFULL apis etc. Below the implementation of this method.
In here you see we are registering one url which will respond when we make a GET request with a HTTP status OK (200). Furthermore you see I'm registering some middleware which ships with chi. You also see I'm using a zapLogger middleware, which I created myself to be able to use zap.Logger as a middleware in chi. Last but not least I added some convenient debugging to log the registered routes on DEBUG level. This is very helpfull when defining bigger APIs with many routes and HTTP verbs.
Below you see the implementation of my zapLogger middleware. It utilizes the RequestID middleware as well to print this in the log as well. I'm also using a nice little trick using defer which allows us to calculate the latency in the request. Defer will invoke only after next.ServeHTTP(ww, r) is called, which goes further down the middleware stack and eventually into your endpoint code. This makes the logger log the latency of all the code which is invoked in between just before it returns the response to the consumer of your webserver. You can read more on the use of defer in Go in this blog post.
Above you also see the logRoutes func that utilizes chi.Walk to walk all the different routes and log them using our zap.Logger on DEBUG level. This will help you to debug issues like what are the exact endpoints in more complex routers.
Last but not least lets have a look on the graceful shutdown part which I also slightly simplified compared to my previous example.
As you might see we are using a subroutine to run the webserver so it runs in the background and then we use a Signal channel to wait for a ctrl+c signal to gracefully shutdown the server.
TL;DR
Finally we came to the end. Below the full server.go file.
You should be able to build and run your webserver now as following, assuming you created the main.go and server.go files. Ofcourse you also initialized your go module.
References
As promised I would include some links to the Go documentation of chi and zap. Furthermore I included a zip file with the full example which you can download and run on your local. For the folks not having golang on their machine you can also use my embedded Docker and docker-compose file to run it using the following:
Many thanks if you managed to make it to the end of this blog post. Please leave me some feedback and share this blog post with your friends and colleagues. Want to read more on Go also check my other blogs on Go.
You have disabled cookies. To leave me a comment please allow cookies at functionality level.
In my last blog I shown you how to upgrade from Raspbian Stretch to Raspbian Buster. As the whole upgrade went smooth it seems there are still some issues with Raspbian Buster. The one which blocked me completely was the ability to run Kodi. Kodi was not able to start due to a GUI error. Therefore I decided to switch back to Raspbian Stretch until Raspbian Buster packages catch up.
Prerequisuites
Before you start a fresh install make sure you have an ethernet cable at hand, as we will need it…
In this blog I want to note down in the shortest way possible how to upgrade your Raspberry Pi from Raspbian Stretch to Raspbian Buster.
First check your current version of Raspbian is Raspbian Stretch. The easiest way to do this is enter the following in your terminal.
In case it states version 8 (jessie) you can check out following blog first to upgrade first to Raspbian Stretch from Jessie. In case your output is version 9 (stretch) please continue below.
First I ensure at least all patche…
In this blog post I would like to cover the recently released Elasticsearch 7.0-rc1 Go client for Elasticsearch. In this blogpost I want to show you a small example with a simple Docker setup using to build a Elasticsearch cluster.
In my previous blogpost I covered some Docker tips and tricks we will utilize again in this blog post.
Initializing your project
To start with we first have to create a project folder. In this folder we will have to initialize our Go module, add our Dockerfile and…
In this blogpost I would like to show you some basic Docker setup I have been using so far in my Go projects. We will be looking at multi-stage Docker builds and how to utilize docker-compose.
In a typical project setup in Go you would most probably start with a file main.go. In addition to that I usually add a Dockerfile for building a Docker image and a docker-compose file to easily spin up my dependencies like databases and queues.
To start we create a new folder to work in and initiales th…