DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Mutual TLS With gRPC Between Python and Go Services
  • Building REST API Backend Easily With Ballerina Language
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Trending

  • Working With Cowork: Don’t Be Confused
  • Why Good Models Fail After Deployment
  • Improving DAG Failure Detection in Airflow Using AI Techniques
  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)
  1. DZone
  2. Data Engineering
  3. Databases
  4. Comparison of Popular Web Frameworks in Go

Comparison of Popular Web Frameworks in Go

Pick a fresh one for your next side project.

By 
Jai Pradeesh user avatar
Jai Pradeesh
·
Sep. 24, 20 · Presentation
Likes (3)
Comment
Save
Tweet
Share
29.1K Views

Join the DZone community and get the full member experience.

Join For Free

Since its launch, Golang (Google’s Go programming language) has become a powerful and popular option to write APIs and web services. This list compiles the seven most popular web frameworks in Go — statistically speaking.

1. Gin

Gin is an HTTP web framework that features a Martini-like API with much better performance — up to 40 times faster. If you need smashing performance, get yourself some Gin.

Features

  • Faster performance: Radix tree-based routing, small memory footprint. No reflection. Predictable API performance.
  • Middleware support: An incoming HTTP request can be handled by a chain of middleware and the final action. For example, Logger, Authorization, GZIP, and finally post a message in the DB.
  • Crash-free: Gin can catch a panic that occurred during an HTTP request and recover it. This way, your server will be always available. As an example - it’s also possible to report this panic to Sentry!
  • JSON validation: Gin can parse and validate the JSON of a request - for example, checking the existence of required values.
  • Routes grouping: Organize your routes better. Authorization required vs non required, different API versions… In addition, the groups can be nested unlimitedly without degrading performance.
  • Error management: Gin provides a convenient way to collect all the errors that occurred during an HTTP request. Eventually, a middleware can write them to a log file, to a database and send them through the network.
  • Rendering built-in: Gin provides an easy to use API for JSON, XML, and HTML rendering.
  • Extendable: Creating a new middleware is so easy, just check out the sample codes.

Installation

Shell
xxxxxxxxxx
1
 
1
go get -u github.com/gin-gonic/gin


Note: Go v1.10+ is required.

Hello World Example

Go
xxxxxxxxxx
1
13
 
1
package main
2
3
import "github.com/gin-gonic/gin"
4
5
func main() {
6
    r := gin.Default()
7
    r.GET("/ping", func(c *gin.Context) {
8
        c.JSON(200, gin.H{
9
            "message": "pong",
10
        })
11
    })
12
    r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
13
}


Source: github.com/gin-gonic/gin

Documentation: gin-gonic.com/docs/

2. Beego

Beego is used for rapid development of 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.

Features

  • With RESTful support, MVC model, and use bee tool to build your apps quickly with features including code hot compile, automated testing, and automated packing and deploying.
  • With intelligent routing and monitoring, it’s able to monitor your QPS, memory and CPU usages, and goroutine status. It provides you full control of your online apps.
  • With powerful built-in modules including session control, caching, logging, configuration parsing, performance supervising, context handling, ORM supporting, and requests simulating. You get a powerful foundation for any type of application.
  • With native Go HTTP package to handle the requests and the efficient concurrence of a goroutine. Your Beego applications can handle massive traffic as Beego are doing in many productions.

Installation

Go
xxxxxxxxxx
1
 
1
go get -u github.com/astaxie/beego


Hello World Example

Go
xxxxxxxxxx
1
 
1
package main
2
3
import "github.com/astaxie/beego"
4
5
func main(){
6
    beego.Run()
7
}


Source: github.com/astaxie/beego

Documentation: beego.me/docs/intro/

3. Echo

Echo positions itself as a high performance and the minimalist web framework.

Features

  • Optimized Router: Highly optimized HTTP router with zero dynamic memory allocation which smartly prioritizes routes.
  • Scalability: Build robust and scalable RESTful API, easily organized into groups.
  • Automatic TLS: Automatically install TLS certificates from Let’s Encrypt.
  • HTTP/2 support: HTTP/2 support improves speed and provides a better user experience.
  • Middleware: Many built-in middleware to use, or the option to 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 responses, including JSON, XML, HTML, File, Attachment, Inline, Stream, or Blob.
  • Templating: Template rendering using any template engine.
  • Extensibility: Customized central HTTP error handling. Easily extendable API.

Installation

Shell
xxxxxxxxxx
1
 
1
go get -u github.com/labstack/echo


Hello World Example

Go
xxxxxxxxxx
1
27
 
1
package main
2
3
import (
4
  "net/http"
5
  "github.com/labstack/echo/v4"
6
  "github.com/labstack/echo/v4/middleware"
7
)
8
9
func main() {
10
  // Echo instance
11
  e := echo.New()
12
13
  // Middleware
14
  e.Use(middleware.Logger())
15
  e.Use(middleware.Recover())
16
17
  // Routes
18
  e.GET("/", hello)
19
20
  // Start server
21
  e.Logger.Fatal(e.Start(":1323"))
22
}
23
24
// Handler
25
func hello(c echo.Context) error {
26
  return c.String(http.StatusOK, "Hello, World!")
27
}


Source: github.com/labstack/echo

Documentation: echo.labstack.com/guide

4. Go kit

Go kit is a programming toolkit for building microservices (or elegant monoliths).

Features

  • Operates in a heterogeneous SOA — expect to interact with mostly non-Go-kit services.
  • RPC as the primary messaging pattern.
  • Pluggable serialization and transport — not just JSON over HTTP.
  • Operate within existing infrastructures — no mandates for specific tools or technologies.

Installation

Shell
xxxxxxxxxx
1
 
1
go get -u github.com/go-kit/kit


Examples: godoc.org/github.com/go-kit/kit/examples

Source: github.com/go-kit/kit

Documentation: godoc.org/github.com/go-kit/kit

5. Fast HTTP

Fast HTTP package is tuned for high performance with zero memory allocations in hot paths. Performance-wise, it is up to 10x faster than `net/http`

Features

  • Optimized for speed: Easily handles more than 100K qps and more than 1M concurrent keep-alive connections on modern hardware.
  • Optimized for low memory usage.
  • The server provides many anti-DoS limits like concurrent connections per client IP, number of requests per connection, and many more.
  • Fasthttp API is designed with the ability to extend existing client and server implementations or to write custom client and server implementations from scratch.

Installation

Shell
xxxxxxxxxx
1
 
1
go get -u github.com/valyala/fasthttp

Hello World Example

Go
xxxxxxxxxx
1
31
 
1
package main
2
3
import (
4
    "flag"
5
    "fmt"
6
    "log"
7
8
    "github.com/valyala/fasthttp"
9
)
10
11
var (
12
    addr     = flag.String("addr", ":8080", "TCP address to listen to")
13
    compress = flag.Bool("compress", false, "Whether to enable transparent response compression")
14
)
15
16
func main() {
17
    flag.Parse()
18
19
    h := requestHandler
20
    if *compress {
21
        h = fasthttp.CompressHandler(h)
22
    }
23
24
    if err := fasthttp.ListenAndServe(*addr, h); err != nil {
25
        log.Fatalf("Error in ListenAndServe: %s", err)
26
    }
27
}
28
29
func requestHandler(ctx *fasthttp.RequestCtx) {
30
    fmt.Fprintf(ctx, "Hello, world!\n\n")
31
}


Source: github.com/valyala/fasthttp

Documentation: godoc.org/github.com/valyala/fasthttp

6. Mux

Mux (gorilla) implements a request router and dispatcher for matching incoming requests to their respective handler.

Features

  • It implements the http.Handler interface so it is compatible with the standard http.ServeMux.
  • Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
  • URL hosts, paths and query values can have variables with an optional regular expression.
  • Registered URLs can be built, or “reversed”, which helps maintaining references to resources.
  • Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.

Installation

Shell
xxxxxxxxxx
1
 
1
go get -u github.com/gorilla/mux

Hello World Example

Go
xxxxxxxxxx
1
11
 
1
func main() {
2
    r := mux.NewRouter()
3
    r.HandleFunc("/articles", ArticlesHandler)
4
    http.Handle("/", r)
5
}
6
7
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
8
    vars := mux.Vars(r)
9
    w.WriteHeader(http.StatusOK)
10
    fmt.Fprintf(w, "Category: %v\n", vars["category"])
11
}


Source: github.com/gorilla/mux

Documentation: gorillatoolkit.org/pkg/mux

7. HttpRouter

HttpRouter is a lightweight high-performance HTTP request router (also called multiplexer or just mux for short).

In contrast to the default mux of Go’s net/http package, this router supports variables in the routing pattern and matches against the request method. It also scales better.

Features

  • Only explicit matches: With other routers, like http.ServeMux, a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like longest match or first registered, first matched. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.
  • Stop caring about trailing slashes: Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don’t like it, you can turn off this behavior.
  • Path auto-correction: Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like ../ or //). Is CAPTAIN CAPS LOCK one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL.
  • Parameters in your routing pattern: Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.
  • Zero Garbage: The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard Handler/HandlerFunc API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary.
  • Performance: Benchmarks speak for themselves.
  • No more server crashes: You can set a Panic handler to deal with panics occurring during handling a HTTP request. The router then recovers and lets the PanicHandler log what happened and deliver a nice error page.
  • Perfect for APIs: The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for OPTIONS requests and 405 Method Not Allowed replies.

Installation

Shell
xxxxxxxxxx
1
 
1
go get -u github.com/julienschmidt/httprouter

Hello World Example

Go
xxxxxxxxxx
1
25
 
1
package main
2
3
import (
4
    "fmt"
5
    "net/http"
6
    "log"
7
8
    "github.com/julienschmidt/httprouter"
9
)
10
11
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
12
    fmt.Fprint(w, "Welcome!\n")
13
}
14
15
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
16
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
17
}
18
19
func main() {
20
    router := httprouter.New()
21
    router.GET("/", Index)
22
    router.GET("/hello/:name", Hello)
23
24
    log.Fatal(http.ListenAndServe(":8080", router))
25
}


Source: github.com/julienschmidt/httprouter

Documentation: godoc.org/github.com/julienschmidt/httprouter

Web Service Requests Framework API

Published at DZone with permission of Jai Pradeesh. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Mutual TLS With gRPC Between Python and Go Services
  • Building REST API Backend Easily With Ballerina Language
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook