gin vs echo

Choosing a Go Framework: Gin vs. Echo

Google engineers Robert Griesemer, Ken Thompson, and Rob Pike conceived Go in 2007. Since its first public release in 2009, Go has influenced how other languages handle various features like network concurrency and data handling.

Go is becoming more popular in the web development community thanks to its built-in net/http library and how simple it is to create a Go HTTP server.

The main challenge of building web applications with Go is that the net/http library requires plenty of outside work and boilerplate code to get functions working efficiently. Its lack of built-in web feature handling makes Go too inflexible to become the go-to language for web developers. Luckily, Go’s many framework and language options solve these challenges in great ways.

Which Golang Framework is Right for My Project?

Let’s take a deep dive into two popular Go frameworks, Gin and Echo, to help you determine which is better suited for your next project. 

Gin, first released in 2015, primarily focuses on performance. Echo, also released in 2015, mainly focuses on being minimal and extensible. Both frameworks are fast, flexible, and reliable but have different use cases, pros and cons, and capabilities. 

Echo is great for handling a vast array of file types and template engines while remaining highly scalable at any level. These features lend themselves well to more extensive projects requiring a concise and straightforward codebase. Meanwhile, Gin can provide concise and easy-to-read code when needed. Its fast performance and highly-detailed error management make it suitable for more experimental projects with personalized code bases.

Let’s examine each framework’s significant features before comparing some sample code. Then, we’ll explore their differences to help you determine which is best suited to your next project.

Gin’s Significant Features

The Gin web framework focuses on performance with a Martini-like API that’s simple to use and understand. Martini is a deprecated API building package that the community enjoyed for its ease of use.

Some great projects that use Gin include gorush, a push notification server written in Go, and photoprism, a useful personal photo management app, among others

Speed

Gin is a fast framework with a small memory footprint. This is mainly because it’s built on HttpRouter, a lightweight, high-performance HTTP request router. HttpRouter and Gin use a radix tree to quickly parse long and complicated route requests.

Error Management with Crash Protection

Gin makes it easy to track errors occurring during an HTTP request. This error tracking makes it simple to create middleware to write these errors to a log file, enabling you to use them however you want.

Gin can also catch and recover a panic during an HTTP request, preventing server downtime. This protection encourages more experimental code.

Echo’s Significant Features

Echo is a high-performance, extensible, and minimalist web framework for Go.

Template Rendering

Echo has excellent template support, enabling users to build using almost any template engine they want. This approach creates flexibility when making larger web applications.

Data Rendering

Echo supports a variety of file types for HTTP responses. This array of file types includes JSON, XML, and HTML as a file, attachment, inline, stream, or blob. This broad file type support creates a robust set of options for user engagement.

Automatic TLS

Security is one of the most critical aspects of building a modern web application. Luckily, Echo allows us to automatically install TLS certificates from Let’s Encrypt, keeping web applications safer by default.

Coding in Echo and Gin

Now that we’ve explored their significant features, let’s examine some sample code from each framework. We’ll create a simple API endpoint and look at some basic middleware in both frameworks to better understand which one will fit your needs.

Using Echo

We must at least update our Go version to version 1.13 or higher to install Echo. Go version 1.12 has limited middleware support, and anything earlier is completely unsupported.
First, create a project folder (outside $GOPATH). Open a terminal and navigate to the space where you would like to create your Echo app. Then, enter the following commands:

	$ mkdir echoapp && cd echoapp
	$ go mod init echoapp
	$ go get github.com/labstack/echo/v4

If you happen to be using Go version 1.14 or earlier, use:

	$ GO111MODULE=on go get github.com/labstack/echo/v4

Now, we’ll create our simple API endpoint. Let’s review the finished code then break it down.

package main

import (
    "net/http"

    "github.com/labstack/echo/v4"
)

func main() {
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "Hello World! I am here!")
    })

    e.Logger.Fatal(e.Start(":8080"))
}

In the code above, we created a simple API endpoint that responds to an HTTP 200 GET request with a “Hello World!” string. First, we made a generic Go file header by using package main and declaring our imports.

Next, we created a new echo object named “e” in our main function, then used Echo’s built-in GET function to create our HTTP request. The GET method requires a path “/” and a handler function func(c echo.Context) to work properly.

We then made a string to return within the GET function. This string will return when the API properly receives a 200 status code.

Finally, we used the line e.Logger.Fatal(e.Start(":8080")) to start our Echo server and handle any errors that may arise when starting it. When we run this program then navigate to localhost:8080, we should see our “hello world” string on the screen. If we navigate with any path included, such as localhost:8080/hello, we encounter an error.

Echo provides a lovely and concise syntax for creating web applications and has great online documentation for troubleshooting errors. We can easily turn the program into a full RESTful API using Echo’s built-in HTTP functions.

Next, let’s look at a simple middleware example from the Echo documentation to explore the framework in greater detail. The Echo team’s online documentation offers many examples and starting points for cool things you can do with the framework. We’ll take a quick look at a logger middleware that writes information about the framework’s usage and connections.

The example custom usage they provide looks like this:

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

This code adds custom configuration to the basic e.Use(middleware.Logger()) function. Echo’s customizable pre-built functions are a great feature.

The code provides this basic output:

method=GET, uri=/, status=200

Here, we looked at a simple example, but there are more complex and powerful options within Echo’s documentation.

Using Gin

Now, we install and use Gin in the same way. We also need Go version 1.13 or newer to install Gin in our workspace. Unlike Echo, we can build Gin apps within the $GOPATH. But we won’t take that approach here, so we can more directly compare the two frameworks.

Let’s start with the same steps as our Echo project:

$ mkdir ginapp && cd ginapp
	$ go mod init ginapp
	$ go get github.com/gin-gonic/gin

Just like our Echo app, if you use Go version 1.14 or earlier, you’ll need to turn on GO111MODULE in the last line.

Now we’re ready to create a basic API endpoint using Gin. The full code is as follows:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello World! We are here!",
        })
    })
    r.Run(":8080")
}

Let’s examine what we just created. First, we made our Go file and imported our necessary libraries. Next, we created the main function and a Gin object named r.

Then we used Gin’s built-in GET function to create our 200 paths and a context object. We returned a JSON data structure with that context object rather than the string we used in Gin. This approach provides a different output visually when we navigate to our page.

Next, we run our server on port 8080. You should see much more detailed terminal output than Echo when running this example. There’s also no logger function needed. Gin handles these errors and shows what IP tried to access what path without any hassle.

Let’s now consider the same basic logger middleware function as Echo:

func main() {
	router := gin.New()
	// LoggerWithFormatter middleware will write the logs to gin.DefaultWriter
	// By default gin.DefaultWriter = os.Stdout
	router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// your custom format
		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
				param.ClientIP,
				param.TimeStamp.Format(time.RFC1123),
				param.Method,
				param.Path,
				param.Request.Proto,
				param.StatusCode,
				param.Latency,
				param.Request.UserAgent(),
				param.ErrorMessage,
		)
	}))
	router.Use(gin.Recovery())
	router.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})
	router.Run(":8080")
}

This example is a bit more lengthy than Echo’s because the example shows the entire main function. Much like Echo, Gin allows you to curate what information to log. This flexibility gives developers similar levels of control in both frameworks for creating middleware.
In the Gin documentation, the code provides this basic output:

::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" "

Coding Differences in Gin Versus Echo

Now that we have examined the same endpoint and middleware in both frameworks, let’s quickly discuss how these coding experiences compare.

The main difference between Gin and Echo in these examples is their syntaxes. Echo has more straightforward and concise syntax, while Gin has more elaborate syntax offering more developer control.

Like the Echo endpoint, you can expand the Gin endpoint into a full RESTful API using Gin’s built-in functions. Both Gin and Echo provide great middleware support and offer developer control. Flexibility is an important aspect of web development, so it’s great to see substantial support from both frameworks.

While these two examples don’t show much variation between the two frameworks, we can begin to see how they differ and apply to various use cases. In the next section, we take a deeper look into how these two frameworks compare in multiple categories.

Comparing the Gin and Echo Frameworks In-Depth

Now that we’ve developed a simple program using each framework, let’s take a closer look at how they compare in various factors affecting developers.

Tech Stack

Both Echo and Gin fit nicely into any tech stack. However, Echo is the better choice for building a cohesive tech stack for the web. It has more robust support for different file types, better data rendering support, and automatic TLS certificates to protect your tech stack.

Ease of Development and Overall Complexity

Developers need simple solutions to build and upkeep at regular intervals. Echo has a much simpler syntax because of its focus on concise code and scalability. Gin requires more complex syntax, but it builds upon the much-loved Martini API language. So, the ease of development is somewhat subjective, depending on your experience and preferences.

Development Capabilities

A good framework needs to be powerful and reliable at all times. Echo offers more power to the developer. While a few features are only in Gin, like robust error management, Echo’s feature set is more well-rounded.

Performance

Gin prides itself on being a lightning-fast framework for Go. By all accounts, this is true, and Gin comes out on top in almost every benchmark. Echo is by no means a slow framework, but it’s no match for the capabilities HttpRouter lends to Gin.

Supporting Libraries and Tech Integrations

Echo supports many more file types and systems than Gin. For example, while sending an HTTP response using a file in Gin may be possible, it likely requires a custom-built middleware or another solution. In Echo, this support is already built-in.

Community Support and Documentation Quality

Community support and documentation quality seem to work out evenly. Gin has a larger community and therefore likely has more support from the public than Echo. However, the Echo team has built out much more robust documentation than Gin.

Both frameworks are well-supported, and deciding which to use depends on personal preference for what makes sense for you and your team.

Conclusion: The Pros and Cons of Gin vs. Echo

Go is an excellent language for web development when paired with the correct framework for your needs. Both Gin and Echo are great options for any developer, and they are staple frameworks for Go web development.

This quick pros and cons list may help you decide which framework to choose:

GinEcho
ProsHigh performance
Crash-free
Great error management
Easy JSON validation
Room for control and experimentation
Great template support
Highly-scalable
Automatic TLS certificates
Broad file type support
Easily extensible
ConsSub-par documentation
Less-concise syntax
Not as flexible in development
Smaller community for support
Less control over minute details
Slower performance

We developers constantly make decisions about our tech stack and development cycles. This task becomes more and more challenging when so many offerings seemingly do the same thing. While Gin and Echo attempt to offer the same capabilities, the frameworks differ and ultimately achieve different goals.

This blog post was created as part of the Mattermost Community Writing Program and is published under the CC BY-NC-SA 4.0 license. To learn more about the Mattermost Community Writing Program, check this out.

Read more about:

Go

Jarrett Azar is a computer scientist and a recent graduate of Muhlenberg College in Allentown, Pennsylvania. He double-majored in Computer Science and Studio Arts (with a focus on photography). Jarrett has a keen interest in a variety of topics, including computers, politics, and sports.