Every organization with a couple of microservices needs to control who can access those services, and under what conditions. An API gateway is an inevitable solution to this problem.

But should you use an existing configurable proxy like Envoy,  Ngnix,  Zuul,  Kong,  aws API gateway ( and the list can go on )? Every one of those projects has its pros and cons, its own configuration language, user community, books, docs, and tutorials.

In this post, I will argue that for you don’t, That everything you need can be achieved using a few golang lines.

This is possible because of the good stuff in "net/http/httputil". This package is an extension of "net/http" and contains network utilities.

One of them is httputil.ReverseProxy , as its name suggests, can handle all the network-related stuff needed to transparently forward an HTTP request, in a line of code: Proxy(targetUrl).ServeHTTP(ctx.Writer, ctx.Request)

It can work with any golang HTTP framework, such as gin or fast-http, one of the fastest server frameworks that exist.

The reverse proxy is not limited to transparent reverse proxying. It can be used to modify intercepted requests and their responses.

For example, lets assume a common scenario, each request needs to be:

  • logged
  • a metric fired
  • routed to a specific micro service, according to a convention in the request path
  • authenticated (setting a request header with un-encrypted user details )
  • authorized
  • rate limited
  • on staging env, in case of a 500, the response body needs to be modified and contain the error message for improved development experience
  • on prod env, it has to contain a hash of the error, to later be used when searching logs.

Configuring NGNIX, ZUUL, or ENVOY to do the above list may be possible, I admit I didn’t try. But is definitely not going to be a walk in the park, and no matter how feature-rich the above proxies are, it can’t be compared to the flexibility of custom code.

#networking #golang #api #go

Why Should You Write Your Own API Gateway — From Scratch
1.60 GEEK