Microservice Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Handlers

Creating routes to APIs in Go is very simple, but using native handlers' options can generate certain complexities, especially regarding the validations. The native muxer does not have a lot of flexibility, so the best option is to seek more productive tool handlers.

Go has a multitude of options for handlers, and perhaps the most explored library model because of the characteristic of writing the low-level language.

When it comes to performance for routers in Go, at the time of release of this book, there is nothing more performative than fasthttp: (https://github.com/valyala/fasthttp).This is a library written using Go that provides low-level language. Fasthttp metrics are outstanding.

Here are the numbers running tests locally to provision static files:

     Running 10s test @ http://localhost:8080
      4 threads and 16 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency   447.99us    1.59ms  27.20ms   94.79%
        Req/Sec    37.13k     3.99k   47.86k    76.00%
      1478457 requests in 10.02s, 1.03GB read
    Requests/sec: 147597.06
    Transfer/sec:    105.15MB

As it can be seen, the number of requests per second exceeds 140,000. However, writing the routes using fasthttp can be as complex as with the native library. Due to this problem, there are some frameworks that do interface for fasthttp. One of these interfaces is the fasthttprouter (https://github.com/buaazp/fasthttprouter), which ultimately creates a number of development facilities without overly compromising the good performance of fasthttp.

Writing routes with extreme performance is very seductive, but we need a balance between performance and stability; here we have a point needing attention. Fasthttp, as well as all its aid interfaces, modifies the native standard of the handler Go to implement the context itself. If there really is a big performance problem, using fasthttp may be something to think about. I do not think this is our case. Therefore, it is recommended to use something that has more compatibility with the standard Go interface.

The most famous option is gorilla/mux (https://github.com/gorilla/mux). Without a doubt, it is one of the most mature and experienced libraries for Go.