Top Web Frameworks in GO
In today's article, I will introduce some web development frameworks in Go. The Google Go language (also known as Golang) has become one of the top choices for writing web services and APIs. It provides useful features for web services, and the language has a large developer community.
Here are the frameworks mostly used for web development in Go:
1. Beego
beego is used for the rapid development of enterprise applications in Go, including RESTful APIs, web apps, and backend services. It is inspired by Tornado, Sinatra, and Flask. beego has some Go-specific features such as interfaces and struct embedding. Here is the beego's architecture:
Beego is composed of four parts:
- Base modules: including log module, config module, governor module;
- Task: is used for running timed tasks or periodic tasks;
- Client: including ORM module, httplib module, cache module;
- Server: including web module. We will support gRPC in the future;
beego might remind you of the Django web framework for Python. The language comes with a bunch of features common to web applications, organized into eight modules that can be used or omitted as needed. In addition, it includes an object relationship map (ORM) for data access, a built-in cache handler, a session handling engine, a logging mechanism, and a library for working with HTTP objects.
beego is similar to Django as a command line tool. For example, you can use the bee command to create a new Beego application or manage existing applications.
Installation
go get github.com/beego/beego/v2@latest
Example
package main
import "github.com/beego/beego/v2/server/web"
func main() {
web.Run()
}
2. Gin
Gin is an HTTP web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to httprouter. If you need performance and good productivity, you will love Gin. In addition, it provides handlers for many common use cases: middleware, file uploads, logging, and front-end HTML component binding to back-end data structures. The data versioning API has also been stable since version 1.x, so future changes won't cause problems with existing Gin apps.
Installation
To install Gin package, you need to install Go and set your Go workspace first.
You first need Go installed (version 1.16+ is required), then you can use the below Go command to install Gin.
go get -u github.com/gin-gonic/gin
Import it in your code:
import "github.com/gin-gonic/gin"
Example
Here is an example of writing a Gin server:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Hello GoLinuxCloud members!",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
Output:
3. Gorilla
Gorilla is a web toolkit for the Go programming language. Currently, these packages are available:
- gorilla/mux is a powerful URL router and dispatcher.
- gorilla/reverse produces reversible regular expressions for regexp-based muxes.
- gorilla/rpc implements RPC over HTTP with codec for JSON-RPC.
- gorilla/schema converts form values to a struct.
- gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values.
- gorilla/sessions saves cookie and filesystem sessions and allows custom session backends.
- gorilla/websocket implements the WebSocket protocol defined in RFC 6455.
- gorilla/csrf provides Cross Site Request Forgery (CSRF) prevention middleware.
- gorilla/handlers is a collection of useful handlers for Go's net/http package.
Installation
Run "go get" pointing to a package. For example, to install gorilla/mux:
go get github.com/gorilla/mux
Example
Let's begin by adding a few URL paths and handlers:
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/products", ProductsHandler)
r.HandleFunc("/articles", ArticlesHandler)
http.Handle("/", r)
}
Paths can have variables. They are defined using the format {name}
 or {name:pattern}
. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
4. Echo
Echo: High performance, extensible, minimalist Go web framework. Here are some of echo's features:
- Optimized Router: Highly optimized HTTP router with zero dynamic memory allocation which smartly prioritizes routes.
- Scalable: Build robust and scalable RESTful API, easily organized into groups.
- Automatic TLS: Automatically install TLS certificates from Let's Encrypt.
- HTTP/2: HTTP/2 support improves speed and provides a better user experience.
- Middleware: Many built-in middlewares to use, or define your own. Middleware can be set at root, group, or route level.
- Data Binding: Data binding for HTTP request payload, including JSON, XML or form-data.
- Data Rendering: API to send variety of HTTP response, including JSON, XML, HTML, File, Attachment, Inline, Stream or Blob.
- Templates: Template rendering using any template engine.
- Extensible: Customized central HTTP error handling. Easily extendable API.
The latest version of Echo supports the last four Go major releases and might work with older versions. As of version 4.0.0, Echo is available as a Go module. Therefore a Go version capable of understanding /vN suffixed imports is required: Any of these versions will allow you to import Echo: github.com/labstack/echo/v4
which is the recommended way of using Echo going forward. For older versions, please use the latest v3 tag.
Installation
// go get github.com/labstack/echo/{version}
go get github.com/labstack/echo/v4
Example
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
// Echo instance
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Routes
e.GET("/", hello)
// Start server
e.Logger.Fatal(e.Start(":1323"))
}
// Handler
func hello(c echo.Context) error {
return c.String(http.StatusOK, "Hello, GoLinuxCloud!")
}
5. Iris
Iris is an efficient and well-designed, cross-platform, web framework with robust set of features. Build your own high-performance web applications and APIs powered by unlimited potentials and portability. If you’re coming from Node.js world, this is the expressjs equivalent for the Go Programming Language. An Iris-powered web application can be deployed as Serverless too - it runs on AWS and Netlify.
Some of the features Iris offers:
- HTTP/2 (Push, even Embedded data)
- Middleware (Accesslog, Basicauth, CORS, gRPC, Anti-Bot hCaptcha, JWT, MethodOverride, ModRevision, Monitor, PPROF, Ratelimit, Anti-Bot reCaptcha, Recovery, RequestID, Rewrite)
- API Versioning
- Model-View-Controller
- Websockets
- gRPC
- Auto-HTTPS
- Builtin support for ngrok to put your app on the internet, the fastest way
- Unique Router with dynamic path as parameter with standard types like :uuid, :string, :int... and the ability to create your own
- Compression
- ....
Installation
go get github.com/kataras/iris/v12
Example
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Use(iris.Compression)
app.Get("/", func(ctx iris.Context) {
ctx.HTML("Hello <strong>%s</strong>!", "GoLinuxcloud!")
})
app.Listen(":8080")
}
6. Revel
Revel.go is also a fully-fledged web framework like Python's Django. It is older than Gin, and is termed as a high productivity web framework. It is an asynchronous, modular, and stateless framework. Unlike the go-restful and Gin frameworks where we created the project ourselves, Revel generates a scaffold for working directly.
Platform features:
- Hot Code Reload: Edit, save, and refresh. Revel compiles your code and templates for you, so you don't miss a beat.
- Comprehensive: Revel provides routing, parameter parsing, validation, session/flash, templating, caching, job running, a testing framework, and even internationalization.
- Flow Control: Revel is built around composable middleware called filters, which implement nearly all request-processing functionality. Developers have the freedom to replace the default filters with custom implementations.
- Migration Friendly
- Reusable MVC Components:Revel has modules. These are reusable MVC components that you can implement across all your projects. No need to copy and paste your code with these.
- Go mod Ready: Revel implements Go's builtin dependency management tool go mod. Making consistent builds a breeze.
- Stateless: Revel provides primitives that keep the web tier stateless for predictable scaling. For example, session data can be stored in the user cookie, and the cache is backed by a memcached cluster, redis or in-memory.
Installation
go install github.com/revel/cmd/revel@latest
In order to run the scaffold tool, we should install one more supplementary package:
go get github.com/revel/cmd/revel
Make sure that $GOPATH/bin
 is in your PATH variable. Some external packages install the binary in the $GOPATH/bin
 directory. If it is in the path, we can access executables system-wide. Here, Revel installs a binary called revel
. You can learn more at Golang GOPATH vs GOROOT Comparison
Example
Now we are ready to start with Revel. Let us create a new project called railAPIRevel
 in github.com/narenaryan
:
revel new railAPIRevel
This creates a project scaffold without writing a single line of code. This is how web frameworks abstract things for quick prototyping. A Revel project layout tree looks like this:
conf/ Configuration directory
app.conf Main app configuration file
routes Routes definition file
app/ App sources
init.go Interceptor registration
controllers/ App controllers go here
views/ Templates directory
messages/ Message files
public/ Public static assets
css/ CSS files
js/ Javascript files
images/ Image files
tests/ Test suites
Out of all those boilerplate directories, three things are important for creating an API. Those are:
- app/controllers
- conf/app.conf
- conf/routes
Controllers are the logic containers that execute the API logic. app.conf
 allows us to set the host, port, and dev mode/production mode and so on. routes defines the triple of the endpoint, REST verb, and function handler (here, controller's function). This means to define a function in the controller and attach it to a route in the routes file.
Summary
We examined six of the best Go web frameworks in this article. This list is not intended to suggest which options are the best or which one you should pick. Regardless of if your favorite is not included on the list, based on your use case, it may still be a superior framework for you.
The ideal framework depends on your use case, so choose the one that works best for your Go project even if some of these frameworks were influenced by others, others were created to cover areas other frameworks didn't, and most of them have comparable functionality.
References
https://go.dev/doc/tutorial/compile-install
https://github.com/beego/beego
https://github.com/gin-gonic/gin
https://www.gorillatoolkit.org/
https://echo.labstack.com/