search
HomeBackend DevelopmentGolangHow to implement a simple API gateway in Golang

##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
// 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.

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()}

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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
How do you iterate through a map in Go?How do you iterate through a map in Go?Apr 28, 2025 pm 05:15 PM

Article discusses iterating through maps in Go, focusing on safe practices, modifying entries, and performance considerations for large maps.Main issue: Ensuring safe and efficient map iteration in Go, especially in concurrent environments and with l

How do you create a map in Go?How do you create a map in Go?Apr 28, 2025 pm 05:14 PM

The article discusses creating and manipulating maps in Go, including initialization methods and adding/updating elements.

What is the difference between an array and a slice in Go?What is the difference between an array and a slice in Go?Apr 28, 2025 pm 05:13 PM

The article discusses differences between arrays and slices in Go, focusing on size, memory allocation, function passing, and usage scenarios. Arrays are fixed-size, stack-allocated, while slices are dynamic, often heap-allocated, and more flexible.

How do you create a slice in Go?How do you create a slice in Go?Apr 28, 2025 pm 05:12 PM

The article discusses creating and initializing slices in Go, including using literals, the make function, and slicing existing arrays or slices. It also covers slice syntax and determining slice length and capacity.

How do you create an array in Go?How do you create an array in Go?Apr 28, 2025 pm 05:11 PM

The article explains how to create and initialize arrays in Go, discusses the differences between arrays and slices, and addresses the maximum size limit for arrays. Arrays vs. slices: fixed vs. dynamic, value vs. reference types.

What is the syntax for creating a struct in Go?What is the syntax for creating a struct in Go?Apr 28, 2025 pm 05:10 PM

Article discusses syntax and initialization of structs in Go, including field naming rules and struct embedding. Main issue: how to effectively use structs in Go programming.(Characters: 159)

How do you create a pointer in Go?How do you create a pointer in Go?Apr 28, 2025 pm 05:09 PM

The article explains creating and using pointers in Go, discussing benefits like efficient memory use and safe management practices. Main issue: safe pointer use.

What are some benefits of using Go?What are some benefits of using Go?Apr 28, 2025 pm 05:08 PM

The article discusses the benefits of using Go (Golang) in software development, focusing on its concurrency support, fast compilation, simplicity, and scalability advantages. Key industries benefiting include technology, finance, and gaming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor