본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

커스텀 플러그인 구성 추가

원문 보기 위키 갱신

커스텀 플러그인 구성 추가 (Add a custom plugin configuration)

커스텀 플러그인에 사용자가 설정할 수 있는 구성 옵션을 추가하는 방법을 알아봐요. schema.lua 파일에 구성 필드를 정의하고, handler.lua 코드에서 그 값을 읽어 플러그인 동작을 바꾸는 과정을 단계별로 설명해요. 마지막에는 Pongo로 구성을 수동으로 검증하고 자동화 테스트까지 추가해 봐요

출처: 문서

본문

TL;DR

커스텀 플러그인의 기능은 어떻게 구성하나요? 플러그인의 schema.lua 파일에 구성 필드를 추가하고, handler.lua에서 그 구성 필드를 사용해 기능을 정의해요.

사전 준비 사항

시리즈 사전 준비 사항

이 페이지는 커스텀 플러그인 개발 시작하기 시리즈의 일부예요.

이 페이지를 완료하기 전에 이전 페이지인 커스텀 플러그인 테스트 추가하기를 먼저 완료하세요.

스키마에 구성 필드 추가하기

schema.lua 파일에 구성 필드를 몇 가지 추가해 볼게요.

  1. schema.lua 파일 상단에 Kong Gateway typedefs 모듈을 포함하세요:

    local typedefs = require "kong.db.schema.typedefs"
    
  2. 앞서 정의한 fields 배열 안에 다음 header_name 타입 정의를 추가하세요:

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

    이 타입 정의는 해당 필드를 null이 될 수 없고 헤더 이름 규칙을 따르는 문자열로 정의해요. 또한 구성 값이 필수가 아니라는 것도 나타내는데, 이는 플러그인을 구성할 때 사용자에게 선택 사항이라는 뜻이에요. 사용자가 값을 지정하지 않을 때 사용될 기본값도 함께 지정하고 있어요.

이제 전체 schema.lua는 다음과 같아요:

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

플러그인 코드에서 구성 값 읽기

handler.lua 파일의 response 함수를 수정해서, 현재 하드코딩된 값 대신 전달되는 conf 파라미터에서 구성 값을 읽도록 해요:

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

수동으로 구성 검증하기

Pongo를 사용해서 업데이트된 구성을 테스트해 볼게요.

  1. Kong Gateway를 시작하고 셸을 열어요:

    pongo shell
    
  2. 데이터베이스 마이그레이션을 실행하고 Kong Gateway를 시작해요:

    kms
    
  3. 테스트용 Gateway Service를 추가해요:

    curl -X POST "http://localhost:8001/services" \
         --no-progress-meter --fail-with-body  \
         --json '{
           "name": "example_service",
           "url": "https://httpbin.konghq.com"
         }'
    
  4. 이번에는 구성 값을 지정해서 플러그인을 활성화해요:

    curl -X POST "http://localhost:8001/services/example_service/plugins" \
         --no-progress-meter --fail-with-body  \
         --json '{
           "name": "my-plugin",
           "config": {
             "response_header_name": "X-CustomHeaderName"
           }
         }'
    
  5. Route를 추가해요:

    curl -X POST "http://localhost:8001/services/example_service/routes" \
         --no-progress-meter --fail-with-body  \
         --json '{
           "name": "example_route",
           "paths": [
             "/mock"
           ]
         }'
    
  6. Route에 요청을 보내요:

    curl -i "http://localhost:8000/mock/anything" \
         --no-progress-meter --fail-with-body 
    

이번에는 응답에서 X-CustomHeaderName을 확인할 수 있을 거예요.

  1. 다음 단계로 넘어가기 전에 Kong Gateway 셸을 종료하세요:
    exit
    

자동화된 구성 테스트 추가하기

  1. spec/01-integration_spec.lua 모듈 안의 setup 함수를 수정해서, 데이터베이스에 추가되는 my-plugin이 response_header_name 필드에 대해 다른 값으로 구성되도록 해요:

    -- 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",
      },
    }
    
  2. 테스트 어설션이 새 헤더 이름과 일치하도록 수정해요:

    -- now validate and retrieve the expected response header 
    local header_value = assert.response(r).has.header("X-CustomHeaderName")
    

    이제 테스트 파일은 다음과 같아야 해요:

    -- Helper functions provided by Kong Gateway, see https://github.com/Kong/kong/blob/master/spec/helpers.lua
    local helpers = require "spec.helpers"
    
    -- matches our plugin name defined in the plugins's schema.lua
    local PLUGIN_NAME = "my-plugin"
    
    -- Run the tests for each strategy. Strategies include "postgres" and "off"
    --   which represent the deployment topologies for Kong Gateway
    for _, strategy in helpers.all_strategies() do
    
      describe(PLUGIN_NAME .. ": [#" .. strategy .. "]", function()
        -- Will be initialized before_each nested test
        local client
    
        setup(function()
    
          -- A BluePrint gives us a helpful database wrapper to
          --    manage Kong Gateway entities directly.
          -- This function also truncates any existing data in an existing db.
          -- The custom plugin name is provided to this function so it mark as loaded
          local blue_print = helpers.get_db_utils(strategy, nil, { PLUGIN_NAME })
    
          -- Using the BluePrint to create a test Route, automatically attaches it
          --    to the default "echo" Service that will be created by the test framework
          local test_route = blue_print.routes:insert({
            paths = { "/mock" },
          })
    
          -- 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",
            },
          }
    
    
          -- start kong
          assert(helpers.start_kong({
            -- use the custom test template to create a local mock server
            nginx_conf = "spec/fixtures/custom_nginx.template",
            -- make sure our plugin gets loaded
            plugins = "bundled," .. PLUGIN_NAME,
          }))
    
        end)
    
        -- teardown runs after its parent describe block
        teardown(function()
          helpers.stop_kong(nil, true)
        end)
    
        -- before_each runs before each child describe
        before_each(function()
          client = helpers.proxy_client()
        end)
    
        -- after_each runs after each child describe
        after_each(function()
          if client then client:close() end
        end)
    
        -- a nested describe defines an actual test on the plugin behavior
        describe("The response", function()
    
          it("gets the expected header", function()
    
            -- invoke a test request
            local r = client:get("/mock/anything", {})
    
            -- validate that the request succeeded, response status 200
            assert.response(r).has.status(200)
    
            -- now validate and retrieve the expected response header 
            local header_value = assert.response(r).has.header("X-CustomHeaderName")
    
            -- validate the value of that header
            assert.equal("response", header_value)
    
          end)
        end)
      end)
    end
    
  3. 테스트를 실행해요:

    pongo run
    

    Pongo에서 테스트가 성공적으로 실행되었다고 보고될 거예요.

관련 리소스

더 알아보기 (Learn more)