Kong에서 API 요청을 보내고, 그 응답 데이터를 가공하여 헤더에 추가하려면 Custom Plugin을 개발해야 합니다. 이를 위해 Lua 코드를 작성하고, ngx 또는 kong.service.request를 활용하여 API 요청을 실행한 후 응답 값을 헤더에 삽입할 수 있습니다.
1️⃣ 개요
✔️ 동작 방식
- Kong이 클라이언트 요청을 받음.
- Kong이 외부 API로 요청을 보냄 (ngx.location.capture 사용).
- 외부 API의 응답을 받아서 Kong의 응답 헤더에 추가.
- 클라이언트가 API를 호출하면, 추가된 헤더 값을 포함하여 응답이 반환됨.
✔️ 주요 사용 함수
- ngx.location.capture(): 내부 요청을 실행하여 API 데이터를 가져옴.
- kong.response.set_header(): 응답 헤더를 설정.
2️⃣ Custom Plugin 개발
🔹 1. 플러그인 폴더 생성
mkdir -p /usr/local/share/lua/5.1/kong/plugins/custom-header-plugin
🔹 2. schema.lua (플러그인 설정) 작성
return {
name = "custom-header-plugin",
fields = {
{ config = {
type = "record",
fields = {
{ api_url = { type = "string", required = true } }, -- 데이터를 요청할 API URL
{ header_name = { type = "string", default = "X-API-Response" } } -- 추가할 헤더 이름
},
} },
},
}
📌 설명
- api_url: 데이터를 가져올 API의 URL
- header_name: 응답에 추가할 헤더 이름 (기본값: X-API-Response)
🔹 3. handler.lua (핵심 로직) 작성
local http = require("resty.http") -- HTTP 요청을 위해 사용
local kong = kong
local CustomHeaderPlugin = {
PRIORITY = 900, -- 플러그인 실행 순서
VERSION = "1.0",
}
function CustomHeaderPlugin:access(conf)
local httpc = http.new()
-- 외부 API에 요청
local res, err = httpc:request_uri(conf.api_url, {
method = "GET",
ssl_verify = false
})
if not res then
kong.log.err("Failed to fetch API response: ", err)
return
end
-- API 응답 값을 헤더에 추가
kong.response.set_header(conf.header_name, res.body)
end
return CustomHeaderPlugin
📌 설명
- http.new()를 사용하여 API 호출을 수행.
- conf.api_url에 GET 요청을 보내 응답을 받음.
- 받은 응답 값을 kong.response.set_header()를 사용하여 응답 헤더에 추가.
3️⃣ Kong에 Custom Plugin 등록
🔹 1. 플러그인 목록에 추가
/etc/kong/kong.conf 또는 /etc/kong/kong.yml 파일 수정:
plugins:
- bundled
- custom-header-plugin
✅ custom-header-plugin을 Kong에 등록.
📌 적용 후 Kong 재시작
kong restart
🔹 2. 특정 서비스에 플러그인 적용
curl -X POST http://localhost:8001/services/{service_id}/plugins \
--data "name=custom-header-plugin" \
--data "config.api_url=http://example.com/api/data" \
--data "config.header_name=X-External-Data"
✅ 이제 해당 서비스에 API 응답 값을 X-External-Data 헤더에 추가하여 반환.
4️⃣ 테스트
🔹 API 호출 (테스트)
curl -i http://localhost:8000/my-service
📤 응답 예시
HTTP/1.1 200 OK X-External-Data: {"key": "value"}
🚀 외부 API의 응답 데이터가 X-External-Data 헤더에 추가됨! 🚀
📌 정리
방법설명
Custom Plugin | Lua 기반 플러그인 작성 |
ngx.location.capture() | 내부 요청을 수행 |
kong.response.set_header() | 응답 헤더 추가 |
Kong 설정 변경 | /etc/kong/kong.conf 수정 후 플러그인 등록 |
728x90