With the popularity of microservice architecture, API gateways have attracted more and more attention. As one of the important components in the microservice architecture, API gateway is an application responsible for distributing requests, routing requests, and filtering requests. Kong has become one of the most popular API gateways among many enterprises because of its flexibility, scalability, and ease of use.
Beego is a framework for rapid development of Go applications that can provide support for RESTful API development. In this article, we will explore how to use Kong for API gateway management in Beego.
First, we need to install Kong. Kong can run on different platforms, including Windows, Linux, Docker, etc. Here we take installing Kong on Linux as an example.
Use yum to install Kong:
$ echo '[bintray--kong-kong-rpm] name=bintray--kong-kong-rpm baseurl=https://kong.bintray.com/kong-community-edition-rpm/centos/$releasever/$basearch/ gpgcheck=0 repo_gpgcheck=0 enabled=1' | sudo tee /etc/yum.repos.d/bintray-kong-kong-rpm.repo $ sudo yum install -y kong
After the installation is complete, run kong to start the Kong service.
Implement the API in Beego and register it in Kong to make it an API accessible to the outside world.
Implementing the API in Beego is relatively simple, so I won’t introduce it too much here. It should be noted that you need to use Kong's Admin API in Beego, so you need to install Kong's official Go client: kong-go-sdk.
$ go get github.com/Kong/go-kong/kong
Before creating the API, we need to have a client object of the Kong Admin API, as shown below:
import "github.com/Kong/go-kong/kong" const KongAdminURL = "http://localhost:8001" func NewKongClient() (*kong.Client, error) { return kong.NewClient(kong.String(KongAdminURL)) }
Then, we can register the API through code. The following is a simple example:
func RegisterAPI(name, upstreamURL, requestHost, stripPath string) error { kongClient, err := NewKongClient() if err != nil { return fmt.Errorf("create kong client error: %v", err) } targetURL, err := url.Parse(upstreamURL) if err != nil { return fmt.Errorf("parse target url error: %v", err) } api := &kong.API{ Name: kong.String(name), Uris: kong.StringSlice("/" + name), UpstreamURL: kong.String(targetURL.String()), RequestHost: kong.String(requestHost), StripUri: kong.Bool(true), StripPath: kong.Bool(stripPath), } _, err = kongClient.APIs().Create(kongContext.Background(), api) if err != nil { return fmt.Errorf("register api to kong error: %v", err) } return nil }
In the above code, we first create a client object of the Kong Admin API, and then use kong.API
to create an API object, such as API name, API corresponding Upstream URL, requested domain name, whether to enable URI removal, whether to enable URI truncation and other options. Finally, we create the API using the client of the Kong Admin API.
Next, we need to configure Kong, add plug-ins and routes to specify the processing of requests and responses.
Kong supports many plugins that allow us to perform more advanced processing on requests and responses. Commonly used plug-ins include rate-limiting
, key-auth
and oauth2
, etc. Here, we will use the rate-limiting
plugin to limit the access speed of the API.
func AddPlugin(apiName string) error { kongClient, err := NewKongClient() if err != nil { return fmt.Errorf("create kong client error: %v", err) } api, err := kongClient.APIs().Get(kongContext.Background(), &apiName) if err != nil { return fmt.Errorf("get api error: %v", err) } plugin := &kong.RateLimiting{ Name: kong.String("rate-limiting"), ConsumerID: nil, Limit: kong.Int(10), Policy: kong.String("local"), } _, err = kongClient.Plugins().Create(kongContext.Background(), &kong.Plugin{ APIID: api.ID, Name: plugin.Name, Config: kong.Configuration{ kong.String("consumer_id"): plugin.ConsumerID, kong.String("limit"): plugin.Limit, kong.String("policy"): plugin.Policy, }, }) if err != nil { return fmt.Errorf("add rate-limiting plugin error: %v", err) } return nil } func AddRoute(apiName string) error { kongClient, err := NewKongClient() if err != nil { return fmt.Errorf("create kong client error: %v", err) } route := &kong.Route{ Name: kong.String(apiName), Paths: kong.StringSlice(fmt.Sprintf("/%s", apiName)), StripPath: kong.Bool(true), PreserveHost: kong.Bool(false), RegexPriority: kong.Int(0), Service: &kong.Service{ ID: kong.String(apiName), }, } _, err = kongClient.Routes().Create(kongContext.Background(), route) if err != nil { return fmt.Errorf("add route error: %v", err) } return nil }
In the above code, we use chain calls to implement Kong’s plug-ins and routing.
For the convenience of demonstration, we only added a current limiting plug-in. By running the CreateRateLimiting function, we will create a plug-in named "rate-limiting" in the Kong gateway and apply it to the API named "api-name". In the code, 10 represents the limit on the number of concurrent requests.
You need to pass in the name of the API when running the method. We need to first create an API in the gateway using the api name. Call the RegisterAPI function to register the API we implemented in the Beego application with the Kong gateway.
After running the AddPlugin function and AddRoute function, our API has been registered in the Kong gateway.
Here we use the method of directly registering the API with the Kong API gateway in the Beego application. In fact, Kong also supports the use of configuration files or other methods to register the API through Kong Manager or Kong Dashboard. However, these methods require us to manually operate in the Kong API gateway background, which is cumbersome and time-consuming.
Finally, we only need to access the API we implemented in Beego through Kong's API gateway. We can use Postman or other REST clients for testing.
In this article, we introduced how to use Kong for API gateway management, including API registration, plug-in addition, and route designation. Using Kong as an API gateway can achieve more flexible, efficient, and secure API management and monitoring.
The above is the detailed content of Using Kong for API gateway management in Beego. For more information, please follow other related articles on the PHP Chinese website!