コンテンツにスキップ
Kong Logo | Kong Docs Logo
  • ドキュメント
    • API仕様を確認する
      View all API Specs すべてのAPI仕様を表示 View all API Specs arrow image
    • ドキュメンテーション
      API Specs
      Kong Gateway
      軽量、高速、柔軟なクラウドネイティブAPIゲートウェイ
      Kong Konnect
      SaaSのエンドツーエンド接続のための単一プラットフォーム
      Kong AI Gateway
      GenAI インフラストラクチャ向けマルチ LLM AI Gateway
      Kong Mesh
      Kuma と Envoy をベースにしたエンタープライズサービスメッシュ
      decK
      Kongの構成を宣言型で管理する上で役立ちます
      Kong Ingress Controller
      Kubernetesクラスタ内で動作し、Kongをプロキシトラフィックに設定する
      Kong Gateway Operator
      YAMLマニフェストを使用してKubernetes上のKongデプロイメントを管理する
      Insomnia
      コラボレーティブAPI開発プラットフォーム
  • Plugin Hub
    • Plugin Hubを探索する
      View all plugins すべてのプラグインを表示 View all plugins arrow image
    • 機能性 すべて表示 View all arrow image
      すべてのプラグインを表示
      AI's icon
      AI
      マルチ LLM AI Gatewayプラグインを使用してAIトラフィックを管理、保護、制御する
      認証's icon
      認証
      認証レイヤーでサービスを保護する
      セキュリティ's icon
      セキュリティ
      追加のセキュリティレイヤーでサービスを保護する
      トラフィック制御's icon
      トラフィック制御
      インバウンドおよびアウトバウンドAPIトラフィックの管理、スロットル、制限
      サーバーレス's icon
      サーバーレス
      他のプラグインと組み合わせてサーバーレス関数を呼び出します
      分析と監視's icon
      分析と監視
      APIとマイクロサービストラフィックを視覚化、検査、監視
      変革's icon
      変革
      Kongでリクエストとレスポンスをその場で変換
      ログ記録's icon
      ログ記録
      インフラストラクチャに最適なトランスポートを使用して、リクエストと応答データをログに記録します
  • サポート
  • コミュニティ
  • Kongアカデミー
デモを見る 無料トライアルを開始
Kong Gateway
3.10.x (最新)
  • Home icon
  • Kong Gateway
  • Plugin Development
  • Get Started
  • Add Plugin Configuration
report-issue問題を報告する
  • Kong Gateway
  • Kong Konnect
  • Kong Mesh
  • Kong AI Gateway
  • Plugin Hub
  • decK
  • Kong Ingress Controller
  • Kong Gateway Operator
  • Insomnia
  • Kuma

  • ドキュメント投稿ガイドライン
  • 3.10.x (latest)
  • 3.9.x
  • 3.8.x
  • 3.7.x
  • 3.6.x
  • 3.5.x
  • 3.4.x (LTS)
  • 3.3.x
  • 2.8.x (LTS)
  • アーカイブ (2.6より前)
  • Introduction
    • Overview of Kong Gateway
    • Support
      • Version Support Policy
      • Third Party Dependencies
      • Browser Support
      • Vulnerability Patching Process
      • Software Bill of Materials
    • Stability
    • Release Notes
    • Breaking Changes
      • Kong Gateway 3.10.x
      • Kong Gateway 3.9.x
      • Kong Gateway 3.8.x
      • Kong Gateway 3.7.x
      • Kong Gateway 3.6.x
      • Kong Gateway 3.5.x
      • Kong Gateway 3.4.x
      • Kong Gateway 3.3.x
      • Kong Gateway 3.2.x
      • Kong Gateway 3.1.x
      • Kong Gateway 3.0.x
      • Kong Gateway 2.8.x or earlier
    • Key Concepts
      • Services
      • Routes
      • Consumers
      • Upstreams
      • Plugins
      • Consumer Groups
    • How Kong Works
      • Routing Traffic
      • Load Balancing
      • Health Checks and Circuit Breakers
    • Glossary
  • Get Started with Kong
    • Get Kong
    • Services and Routes
    • Rate Limiting
    • Proxy Caching
    • Key Authentication
    • Load-Balancing
  • Install Kong
    • Overview
    • Kubernetes
      • Overview
      • Install Kong Gateway
      • Configure the Admin API
      • Install Kong Manager
    • Docker
      • Using docker run
      • Build your own Docker images
    • Linux
      • Amazon Linux
      • Debian
      • Red Hat
      • Ubuntu
    • Post-installation
      • Set up a data store
      • Apply Enterprise license
      • Enable Kong Manager
  • Kong in Production
    • Deployment Topologies
      • Overview
      • Kubernetes Topologies
      • Hybrid Mode
        • Overview
        • Deploy Kong Gateway in Hybrid mode
        • Incremental Configuration Sync
      • DB-less Deployment
      • Traditional
    • Running Kong
      • Running Kong as a non-root user
      • Securing the Admin API
      • Using systemd
    • Access Control
      • Start Kong Gateway Securely
      • Programatically Creating Admins
      • Enabling RBAC
      • Workspaces
    • Licenses
      • Overview
      • Download your License
      • Deploy Enterprise License
      • Using the License API
      • Monitor Licenses Usage
    • Networking
      • Default Ports
      • DNS Considerations
      • Network and Firewall
      • CP/DP Communication through a Forward Proxy
      • PostgreSQL TLS
        • Configure PostgreSQL TLS
        • Troubleshooting PostgreSQL TLS
    • Kong Configuration File
    • Environment Variables
    • Serving a Website and APIs from Kong
    • Secrets Management
      • Overview
      • Getting Started
      • Secrets Rotation
      • Advanced Usage
      • Backends
        • Overview
        • Environment Variables
        • AWS Secrets Manager
        • Azure Key Vaults
        • Google Cloud Secret Manager
        • HashiCorp Vault
      • How-To
        • Securing the Database with AWS Secrets Manager
      • Reference Format
    • Keyring and Data Encryption
    • Monitoring
      • Overview
      • Prometheus
      • StatsD
      • Datadog
      • Health Check Probes
      • Expose and graph AI Metrics
    • Tracing
      • Overview
      • Writing a Custom Trace Exporter
      • Tracing API Reference
    • Resource Sizing Guidelines
    • Blue-Green Deployments
    • Canary Deployments
    • Clustering Reference
    • Performance
      • Performance Testing Benchmarks
      • Establish a Performance Benchmark
      • Improve performance with Brotli compression
    • Logging and Debugging
      • Log Reference
      • Dynamic log level updates
      • Customize Gateway Logs
      • Debug Requests
      • AI Gateway Analytics
      • Audit Logging
    • Configure a gRPC service
    • Use the Expressions Router
    • Outage Handling
      • Configure Data Plane Resilience
      • About Control Plane Outage Management
    • Upgrade and Migration
      • Upgrading Kong Gateway 3.x.x
      • Backup and Restore
      • Upgrade Strategies
        • Dual-Cluster Upgrade
        • In-Place Upgrade
        • Blue-Green Upgrade
        • Rolling Upgrade
      • Upgrade from 2.8 LTS to 3.4 LTS
      • Migrate from OSS to Enterprise
      • Migration Guidelines Cassandra to PostgreSQL
      • Migrate to the new DNS client
      • Breaking Changes
    • FIPS 140-2
      • Overview
      • Install the FIPS Compliant Package
    • Authenticate your Kong Gateway Amazon RDS database with AWS IAM
    • Verify Signatures for Signed Kong Images
    • Verify Build Provenance for Signed Kong Images
  • Kong AI Gateway
    • Overview
    • Get started with AI Gateway
    • LLM Provider Integration Guides
      • OpenAI
      • Cohere
      • Azure
      • Anthropic
      • Mistral
      • Llama2
      • Vertex/Gemini
      • Amazon Bedrock
    • LLM Library Integration Guides
      • LangChain
    • AI Gateway Analytics
    • Expose and graph AI Metrics
    • AI Gateway Load Balancing
    • AI Gateway plugins
  • Kong Manager
    • Overview
    • Enable Kong Manager
    • Get Started with Kong Manager
      • Services and Routes
      • Rate Limiting
      • Proxy Caching
      • Authentication with Consumers
      • Load Balancing
    • Authentication and Authorization
      • Overview
      • Create a Super Admin
      • Workspaces and Teams
      • Reset Passwords and RBAC Tokens
      • Basic Auth
      • LDAP
        • Configure LDAP
        • LDAP Service Directory Mapping
      • OIDC
        • Configure OIDC
        • OIDC Authenticated Group Mapping
        • Migrate from previous configurations
      • Sessions
      • RBAC
        • Overview
        • Enable RBAC
        • Add a Role and Permissions
        • Create a User
        • Create an Admin
    • Networking Configuration
    • Workspaces
    • Create Consumer Groups
    • Sending Email
    • Troubleshoot
    • Strengthen Security
  • Develop Custom Plugins
    • Overview
    • Getting Started
      • Introduction
      • Set up the Plugin Project
      • Add Plugin Testing
      • Add Plugin Configuration
      • Consume External Services
      • Deploy Plugins
    • File Structure
    • Implementing Custom Logic
    • Plugin Configuration
    • Accessing the Data Store
    • Storing Custom Entities
    • Caching Custom Entities
    • Extending the Admin API
    • Writing Tests
    • Installation and Distribution
    • Proxy-Wasm Filters
      • Create a Proxy-Wasm Filter
      • Proxy-Wasm Filter Configuration
    • Plugin Development Kit
      • Overview
      • kong.client
      • kong.client.tls
      • kong.cluster
      • kong.ctx
      • kong.ip
      • kong.jwe
      • kong.log
      • kong.nginx
      • kong.node
      • kong.plugin
      • kong.request
      • kong.response
      • kong.router
      • kong.service
      • kong.service.request
      • kong.service.response
      • kong.table
      • kong.telemetry.log
      • kong.tracing
      • kong.vault
      • kong.websocket.client
      • kong.websocket.upstream
    • Plugins in Other Languages
      • Go
      • Javascript
      • Python
      • Running Plugins in Containers
      • External Plugin Performance
  • Kong Plugins
    • Overview
    • Authentication Reference
    • Allow Multiple Authentication Plugins
    • Plugin Queuing
      • Overview
      • Plugin Queuing Reference
    • Dynamic Plugin Ordering
      • Overview
      • Get Started with Dynamic Plugin Ordering
    • Redis Partials
    • Datakit
      • Overview
      • Get Started with Datakit
      • Datakit Configuration Reference
      • Datakit Examples Reference
  • Admin API
    • Overview
    • Declarative Configuration
    • Enterprise API
      • Information Routes
      • Health Routes
      • Tags
      • Debug Routes
      • Services
      • Routes
      • Consumers
      • Plugins
      • Certificates
      • CA Certificates
      • SNIs
      • Upstreams
      • Targets
      • Vaults
      • Keys
      • Filter Chains
      • Licenses
      • Workspaces
      • RBAC
      • Admins
      • Consumer Groups
      • Event Hooks
      • Keyring and Data Encryption
      • Audit Logs
      • Status API
  • Reference
    • kong.conf
    • Injecting Nginx Directives
    • CLI
    • Key Management
    • The Expressions Language
      • Overview
      • Language References
      • Performance Optimizations
    • Rate Limiting Library
    • WebAssembly
    • Event Hooks
    • FAQ
On this pageOn this page
  • Prerequisites
  • Step by Step
    • Add configuration fields to the schema
    • Read configuration values from plugin code
    • Manually validate configuration
    • Add automated configuration testing
  • What’s next?

このページは、まだ日本語ではご利用いただけません。翻訳中です。

Add Plugin Configuration

The following is a step by step guide for adding configuration to custom plugins on Kong Gateway.

Prerequisites

This page is the third chapter in the Getting Started guide for developing custom plugins. These instructions refer to the previous chapters in the guide and require the same developer tool prerequisites.

Step by Step

Now that you have a basic plugin project with testing, the following steps guide you through adding configuration capabilities to the plugin code.

Add configuration fields to the schema

Let’s add some configuration fields to our schema.lua file allowing us to make the plugin behavior configurable without having to redeploy or restart.

Kong Gateway provides a module of base type definitions that can help us with common types related to API gateway plugins.

At the top of the schema.lua file we include the Kong Gateway typedefs module with the statement:

local typedefs = require "kong.db.schema.typedefs"

Below is a Lua snippet showing a typical configuration field that defines a field named response_header_name.

Here we use the header_name type definition which defines the field to be a string that cannot be null and conforms to the gateway rules for header names.

 { response_header_name = typedefs.header_name {
     required = false,
     default = "X-MyPlugin" } },

The definition also indicates that the configuration value is not required, which means it’s optional for the user when configuring the plugin. We also specify a default value that will be used when a user does not specify a value.

Place this definition in the schema.lua file within the fields array we defined earlier.

The full schema.lua now looks like the following:

local typedefs = require "kong.db.schema.typedefs"

local PLUGIN_NAME = "my-plugin"

local schema = {
  name = PLUGIN_NAME,
  fields = {
    { config = {
        type = "record",
        fields = {
          { response_header_name = typedefs.header_name {
            required = false,
            default = "X-MyPlugin" } },
        },
      },
    },
  },
}

return schema

Now the plugin can accept a configuration value, let’s see how to read it from the plugin logic code.

Read configuration values from plugin code

Modify the handler.lua file response function to read the configuration value from the incoming conf parameter instead of the current hardcoded value.

The function now looks like the following:

function MyPluginHandler:response(conf)
    kong.response.set_header(conf.response_header_name, "response")
end

That’s all that’s required, the plugin can now be dynamically configured at runtime. Next, let’s validate our changes work as expected with manual and automated tests.

Manually validate configuration

In the previous chapter on testing we showed how to use Pongo to run a shell and manually validate the plugins behavior. Repeat that process here to validate the plugins new configurable behavior.

Launch the gateway and open a shell:

pongo shell

From within the shell, run the database migrations and start Kong Gateway:

kms

Add a test service:

curl -i -s -X POST http://localhost:8001/services \
   --data name=example_service \
   --data url='https://httpbin.konghq.com'

And create our plugin instance, but this time provide the configuration value as data in the POST request to the Admin API:

curl -is -X POST http://localhost:8001/services/example_service/plugins \
    --data 'name=my-plugin' --data 'config.response_header_name=X-CustomHeaderName'

Add a route so we can send test requests:

curl -i -X POST http://localhost:8001/services/example_service/routes \
   --data 'paths[]=/mock' \
   --data name=example_route

And proxy a request through our test route:

curl -i http://localhost:8000/mock/anything

This time we should see our configured header in the response:

...
[X-CustomHeaderName] = 'response'
...

Now that my-plugin is configurable and we’ve validate the behavior, let’s look at how we can build an automated approach to validate our changes.

Add automated configuration testing

Without changing anything we can re-run the tests we already have with pongo run:

pongo run

Our tests should continue to report successful:

[  PASSED  ] 2 tests.

Our test is still valid because the default value in our configurable field matches the value in our test case. Let’s see how we can validate a different value for the response_header_name field.

Modify the setup function inside the spec/01-integration_spec.lua module so that the my-plugin that is added to the database is configured with a different value for the response_header_name field.

Here is the code:

-- Add the custom plugin to the test route
blue_print.plugins:insert {
  name = PLUGIN_NAME,
  route = { id = test_route.id },
  config = {
    response_header_name = "X-CustomHeaderName",
  },
}

Use Pongo to re-run the test:

pongo run

If we’ve changed everything properly, our tests should fail and produce a report similar to the following:

/kong-plugin/spec/my-plugin/01-integration_spec.lua:75: Expected header:
(string) 'X-MyPlugin'
But it was not found in:
(table: 0x484c9942b180) {
  [Connection] = 'keep-alive'
  [Content-Length] = '1016'
  [Content-Type] = 'application/json'
  [Date] = 'Mon, 18 Mar 2024 13:49:06 GMT'
  [Server] = 'mock-upstream/1.0.0'
  [Via] = 'kong/3.10.x'
  [X-CustomHeaderName] = 'response'
  [X-Kong-Proxy-Latency] = '1'
  [X-Kong-Request-Id] = '92dfcf56b12b0d29f54ed9295aed6356'
  [X-Kong-Upstream-Latency] = '2'
  [X-Powered-By] = 'mock_upstream' }
stack traceback:
        /kong-plugin/spec/my-plugin/01-integration_spec.lua:75: in function </kong-plugin/spec/my-plugin/01-integration_spec.lua:66>
[  FAILED  ] /kong-plugin/spec/my-plugin/01-integration_spec.lua:66: my-plugin: [#postgres] The response gets a 'X-MyPlugin' header (4.58 ms)

The tests fail because while we updated the plugin configuration, we did not update the expected header name in the test case. To fix the tests, modify the test assertion to match our configured header name.

Change this line:

local header_value = assert.response(r).has.header("X-MyPlugin")

To expect the new configured header name:

local header_value = assert.response(r).has.header("X-CustomHeaderName")

When you re-run the tests:

pongo run

Pongo should report a successful test run:

[  PASSED  ] 2 tests.

What’s next?

You now have a complete development environment and a framework for adding capabilities to your custom plugin. Next we’ll show you how to connect to external services from within your plugin code and later show you how to deploy your plugin onto your Kong Gateway dataplanes so you can put your business logic into production.


前へ Add Plugin Testing
次へ Consume External Services
Thank you for your feedback.
Was this page useful?
情報が多すぎる場合 close cta icon
Kong Konnectを使用すると、より多くの機能とより少ないインフラストラクチャを実現できます。月額1Mリクエストが無料。
無料でお試しください
  • Kong
    APIの世界を動かす

    APIマネジメント、サービスメッシュ、イングレスコントローラーの統合プラットフォームにより、開発者の生産性、セキュリティ、パフォーマンスを大幅に向上します。

    • 製品
      • Kong Konnect
      • Kong Gateway Enterprise
      • Kong Gateway
      • Kong Mesh
      • Kong Ingress Controller
      • Kong Insomnia
      • 製品アップデート
      • 始める
    • ドキュメンテーション
      • Kong Konnectドキュメント
      • Kong Gatewayドキュメント
      • Kong Meshドキュメント
      • Kong Insomniaドキュメント
      • Kong Konnect Plugin Hub
    • オープンソース
      • Kong Gateway
      • Kuma
      • Insomnia
      • Kongコミュニティ
    • 会社概要
      • Kongについて
      • お客様
      • キャリア
      • プレス
      • イベント
      • お問い合わせ
  • 利用規約• プライバシー• 信頼とコンプライアンス
© Kong Inc. 2025