Building Microservice using Golang Echo framework

Suman Das
Crux Intelligence
Published in
5 min readOct 2, 2019

This topic explains how to build a Microservice using the Golang web framework Echo.

Go is an increasingly popular language choice for creating web applications due to the flexibility and performance built into the `net/http` standard library package that comes with the language. The `net/http` package provides many useful and powerful primitives, such as its webserver implementation, request and response types, and methods, uniform resource location router, as well as a clean handler interface and function type declaration.

While the stdlib of Go is capable enough to create a production-ready microservice, a project might require functionality that is not available in the stdlib. Various frameworks extend the functionality of Go, one of which is the Echo. Echo is a performance-focused, extensible, open-source Go web application framework. It is a minimalist web framework that stands between stdlib + router and a full-stack web framework. It comes with extensible middleware, central HTTP error handling, and template rendering for any template engine.

Creating a simple web application using the Echo framework

When we develop a Go web application with Echo, it helps us start our project with a sturdy package structure. However, here, we focus on getting a microservice up and running in the Echo framework with minimal programming.

Table of contents:

  1. Creating Entrypoint
  2. Using Handlers
  3. Defining Routes
  4. Defining Middleware
  5. Running the MicroService

1. Creating EntryPoint

Let’s start with the entry point of our application. It should be in the main package. The filename can be anything. Let’s say we will use the filename as “main.go”. Go program only can start on the main package (“package main”).

EntryPoint

The preceding code block instantiates a new Echo server. The server is started on port 8000 on the final line of the main function. We have to import the github.com/labstack/echopackage for using the echo framework. Now since our server is running let’s expose some rest endpoints for our application.

2. Using Handlers

Handlers are the meat of web application development where all the business logic is stored. A handler is primarily where the application converts the input into an output. As we know, Go’s `net/http` package defines a handler function signature as a function that takes in an “http.ResponseWriter” and a “http.Request”. The handler type in Echo is a function that takes in an Echo “Context”, and returns an error.

type HandlerFunc func(Context) error

Within the Echo Context, we have access to the request as well as the response writer if we want to access them directly. Echo also provides useful helper methods off of the Echo Context.

Let’s start by creating some handler functions.

2.1. Handler function reading QueryParam

Echo provides an easy mechanism for drawing variables from the built-in Context object. “GetCats” function extracts QueryParam specified by the caller. Using the QueryParams we can send a response to the caller.

The above code reads the QueryParam name and type specified by the caller. Then return the response in String format. We need to import the “net/http” package to send HTTP status code in the response. We also need to import the “fmt” package to format the message string.

2.2. Handler function reading PathVariable

Update the above handler function which can read Pathvariable along with QueryParams and return a response.

The above code reads the PathVariable along with QueryParam. Depending upon the PathVariable value, it will return the response in JSON/String format. PathVariable accepts values either JSON or string. If any other value is specified then it returns HTTP StatusBadRequest.

2.3. Handler function reading Request Body

Proceed to write a handler function that extracts RequestBody specified by the caller. After reading the RequestBody we can send a response to the caller.

Now that our business logic is in place, we can proceed with defining the routing logic for the handlers.

3. Defining Routes

We need to define routes to our handlers. Within the Echo server instance, there are helper methods to add the target path to route to a handler. The following is a code block that routes to our handler functions.

In our example, we are adding a cats entry to the Echo server’s router. Whenever an HTTP POST request with a target path of /cats comes into the server, the router will run the AddCat handler function.

4. Defining Middleware

Think of middleware as a wrapper for the handlers we create. Sometimes, there are use cases where the same application logic needs to be applied to a multitude of resources within an application. A prime example of this type of logic is protecting the resources behind an authentication mechanism. An Echo middleware is defined as a function that takes the next function to call as a parameter and returns an Echo handler. By having the parameter be the next handler function to call, we are able to build a chain of handlers:

Middleware Request Processing Pipeline

Middleware functions are a great way to enrich requests with common functionality , that can be reusable across the application handler code. The use of middleware will significantly simplify your code and allow for greater reuse across your application. This middleware is executed after router processes the request and has full access to echo.Context API. When defining a new route, we can optionally register middleware just for it.

e := echo.New()
e.GET("/", <Handler>, <Middleware...>)

Echo provides a lot of built-in middlewares, such as, BodyLimit, Logger, Gzip, Recover, BasicAuth, JWTAuth, Secure, CORS, and Static, which can be used out of the box.

We can use the default middleware Logger.

e.Use(middleware.Logger())

We can further modify each Middleware provided by Echo. Each middleware has the WithConfig method which can be used for customization. Let’s, see how we can customize Logger middleware :

e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "method=${method}, uri=${uri}, status=${status}\n",
}))

We can also write custom middleware. Please find below a sample code of how to write custom middleware.

We can use the custom middleware same as regular middleware

e.Use(serverHeader)

5. Run the Microservice

Now we are ready to go. After completing the earlier steps, we can run our application using the command “go run main.go”. Our application will be running on port 8000.

If you would like to refer to the full code, do check
https://github.com/sumanentc/echo-example.git

Follow Cuddle on Instagram and Dribbble and know more about how we are building the future of Business Intelligence! ⚡

--

--