0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

KongのRoute Transformer Advanced Pluginでアクセス先を変更する

Posted at

Kong GatewayにはRoute Transformer Advanced Pluginというものがある。
これの挙動を調べた時のメモ。
この記事は自分用のメモなので、説明は少なめ。 

Route Transformer Advanced Pluginとは

Serviceの宛先を無視して、別のパスに転送してくれるプラグイン。
それだけだとあまり価値がないように見えるが、テンプレートと組み合わせることで柔軟なパス変換が可能になる。

例えば、APIのリクエスト先が/id/<ユーザID>みたいになっている時、APIの仕様が変わって/user/<ユーザID>/idとなったとする。
この場合なケースでも、Route Transformer Advancedを使うとクライアント側はアクセス先を変更せず、展開済みのServiceも変更せずにアドレスの書き換えを簡単に行う事が出来る。

前提

以下が利用できるようになっているものとする。

  • Kong Gateway
  • deck CLI

動作確認

ここでは先程述べたような、クライアントが/id/<ユーザID>にアクセスした時、実際は/user/<ユーザID>/idを参照するように変えてみる。

Service、Routeを作成する。

cat <<EOF | deck gateway sync -
_format_version: "3.0"
services:
- name: example-service
  host: httpbin.org
  port: 443
  protocol: https
  routes:
  - name: example-route
    paths:
    - ~/id/(?<user_id>[0-9]+)
    protocols:
    - http
    - https
    strip_path: true
EOF

Serviceはhttpbin.orgを使い、アクセスした際にどのようなリクエストを投げたかが分かるようにする。
Pathに~/id/(?<user_id>[0-9]+)を指定しているが、これは前述のテンプレートを使うために記載している。
?<user_id>でuser_idというグループ名を定義し、[0-9]+でIDを取得している。
なお、3.0以降は正規表現を指定する場合はPathの先頭が~で始まる必要がある(CHANGELOG)。

次にRouteにRoute Transformer Advancedプラグインを適用する。
ここではKong Managerから設定する。
RouteからPluginを選択して以下のRoute Transformer AdvancedをEnableにする。
20240829141309.png

設定時、設定項目としては以下がある。

  • Host: 転送先アドレス
  • Path: 転送先パス
  • Port: 転送先ポート
  • Instance Name: Kong内での管理用の名前
  • Tags: Kong内での管理用のタグ
  • Escape Path: Routeのパスに" "などがあれば"%20"のようにエスケープする

ここでは以下のように設定する。

  • Path: /anything/user/$(uri_captures.user_id)/id
  • Instance Name: httpbing-route-transfer

Pathの/anythingでhttpbin.orgでリクエストの内容を表示するサービス(https://httpbin.org/anything)を参照させている。
それ以下のパスはサービスには影響しないため、どのようなパスを指定しても基本的には問題ない。
/user/$(uri_captures.user_id)/idが変換後のパスであり、$(uri_captures.user_id)でRouteのPathで正規表現でグループ化したuser_idを指定するようにしている。
その他の項目はデフォルト値であればRouteの設定を引き継ぐので、特に指定する必要はない。

設定後、実際にアクセスして意図通り変換されているか確認する。

curl "localhost:8000/id/0123"

結果は以下となった。

:(省略)
  "url": "https://localhost/anything/user/0123/id"
:(省略)

意図通りのパスにアクセスしたことが確認できた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?