A Simple way to Send HTTP Error Codes With Golang and Gin Gonic

A simple way to handle errors in APIs

Amrit Pal Singh
Level Up Coding

--

Go is a very popular language for good reason. It is a simple language with performance as good as a low-level language like C++. Acceptance of Golang in web development is booming at a high rate.

The Gin web framework uses a custom version of HttpRouter, that navigates through your API routes faster than most frameworks out there. Gin claims to be 40 times faster than Martini.

While developing APIs for your service you might want a way to handle the errors/exceptions and return appropriate HTTP error code and message to the client. The following scheme makes it very easy to handle such situations.

Response Dispatcher

Implementation of response dispatcher looks like this:

The above method accepts the Context and Response structure that generalizes the response.

This method can be used to send various HTTP error codes along with error messages to the clients. Usage of the dispatcher looks like this:

Wrapping it up

There are thousands of ways to send Error responses from the APIs, this is one of those. Whenever I start a new project, I prefer a method like this to make my life easy.

--

--

Cloud Software Engineer | Product Development | I write about Tech and Travel | Profile https://bit.ly/3dNxaiK | Golang Web Dev Course - https://bit.ly/go-gin