How to implement a simple API gateway in Golang

藏色散人
Release: 2020-08-31 17:07:02
forward
3669 people have browsed it

##The following is the

Golangtutorial column Let me introduce to you how to implement a simple API gateway in Golang. I hope it will be helpful to friends who need it!

How to implement a simple API gateway in Golang

In a recent project, the microservice architecture-

go-kit was used for back-end development. In the microservice architecture style, a large application is split into multiple small service systems. These small systems can be self-contained, which means that these small systems can have their own databases, frameworks and even languages. , so we need to design an API Gateway (API Gataway). In fact, there are many ready-made implementation frameworks on the Internet, but the requirements of this project are relatively simple, so we will use Golang Implement it yourself.

Implementation

API gateway is a server and the only entrance to the system. From an object-oriented design perspective, it is similar to the facade pattern. The API gateway encapsulates the internal architecture of the system and provides a customized API for each client. It may also have other responsibilities such as authentication, monitoring, load balancing, caching, request sharding and management, and static response handling.

There are many technologies used to implement API gateways, which are roughly divided into the following categories:

    Universal reverse proxy:
  • Nginx, Haproxy,…
  • Network programming framework:
  • Netty, Servlet,…
  • API gateway framework:
  • Spring Cloud Gateway, Zuul, Zuul2,...
The most basic function of API gateway is reverse proxy. There are many ways to implement it. This article will implement a simple reverse proxy based on the

ReverseProxy type in the standard library net/http/httputil package. The implementation of reverse proxy mainly involves func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy and type ReverseProxy.

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy
Copy after login
// NewSingleHostReverseProxy returns a new ReverseProxy that routes// URLs to the scheme, host, and base path provided in target. If the// target's path is "/base" and the incoming request was for "/dir",// the target request will be for /base/dir.// NewSingleHostReverseProxy does not rewrite the Host header.// To rewrite Host headers, use ReverseProxy directly with a custom// Director policy.func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
	targetQuery := target.RawQuery
	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
		if targetQuery == "" || req.URL.RawQuery == "" {
			req.URL.RawQuery = targetQuery + req.URL.RawQuery		} else {
			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery		}
		if _, ok := req.Header["User-Agent"]; !ok {
			// explicitly disable User-Agent so it's not set to default value
			req.Header.Set("User-Agent", "")
		}
	}
	return &ReverseProxy{Director: director}}
Copy after login

NewSingleHostReverseProxy Returns a new ReverseProxy that routes URLs requests to the specified of target scheme, host, base path. The

// ReverseProxy is an HTTP Handler that takes an incoming request and// sends it to another server, proxying the response back to the// client.type ReverseProxy struct {
	// Director must be a function which modifies
	// the request into a new request to be sent
	// using Transport. Its response is then copied
	// back to the original client unmodified.
	// Director must not access the provided Request
	// after returning.
	Director func(*http.Request)

	Transport http.RoundTripper

	FlushInterval time.Duration

	ErrorLog *log.Logger

	BufferPool BufferPool	// ModifyResponse is an optional function that modifies the
	// Response from the backend. It is called if the backend
	// returns a response at all, with any HTTP status code.
	// If the backend is unreachable, the optional ErrorHandler is
	// called without any call to ModifyResponse.
	//
	// If ModifyResponse returns an error, ErrorHandler is called
	// with its error value. If ErrorHandler is nil, its default
	// implementation is used.
	ModifyResponse func(*http.Response) error

	ErrorHandler func(http.ResponseWriter, *http.Request, error)}
Copy after login

ReverseProxy type has two important attributes, namely Director and ModifyResponse, both of which are function types. When receiving a client request, the ServeHTTP function first calls the Director function to modify the received request body, such as modifying the request's target address, request header, etc.; then uses the modified request body Initiate a new request, receive the response, call the ModifyResponse function to modify the response, and finally copy the modified response body and respond to the client, thus realizing the entire reverse proxy process.

In

NewSingleHostReverseProxy the source code has parsed the incoming URLs and completed the modification of Director, we only need to call Just pass the NewSingleHostReverseProxy function and pass in the URL of the target server, and a simple reverse proxy is completed.

Code

The example code only involves the

user and auth modules in the microservice. You can modify some parts according to actual needs.

package mainimport (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings")type handle struct {
	host string
	port string}type Service struct {
	auth *handle
	user *handle}func (this *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var remote *url.URL	if strings.Contains(r.RequestURI, "api/auth") {
		remote, _ = url.Parse("http://" + this.auth.host + ":" + this.auth.port)
	} else if strings.Contains(r.RequestURI, "api/user") {
		remote, _ = url.Parse("http://" + this.user.host + ":" + this.user.port)
	} else {
		fmt.Fprintf(w, "404 Not Found")
		return
	}
	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.ServeHTTP(w, r)}func startServer() {
	// 注册被代理的服务器 (host, port)
	service := &Service{
		auth: &handle{host: "127.0.0.1", port: "8081"},
		user: &handle{host: "127.0.0.1", port: "8082"},
	}
	err := http.ListenAndServe(":8888", service)
	if err != nil {
		log.Fatalln("ListenAndServe: ", err)
	}}func main() {
	startServer()}
Copy after login

The above is the detailed content of How to implement a simple API gateway in Golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!