Home > Article > Backend Development > How to implement a simple API gateway in Golang
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.
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:
,
Haproxy,…
,
Servlet,…
,
Zuul,
Zuul2,...
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
// 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}}
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)}
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.
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.
The example code only involves theuser
and
authmodules 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()}
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!