如何在Kong API网关(DB-Less模式)中返回静态响应
在Kong DB-Less模式下返回静态OAS文件
要在Kong的DB-Less模式中实现直接返回静态YAML/JSON格式的OAS响应,你不需要配置实际的后端服务,借助Kong的官方插件就能轻松完成。这里推荐两种简单可行的方案:
方案1:使用echo插件(推荐)
echo插件是Kong专门用来返回自定义静态响应的插件,它会在请求到达后端之前直接返回你配置的内容,完全不需要转发请求。
以下是更新后的完整kong.yaml配置:
_format_version: "2.1" _transform: true services: - name: service1 url: http://service1:port/sample-path # 新增的静态响应服务 - name: oas-static-service # 用一个dummy地址即可,因为echo插件不会转发请求到后端 url: http://localhost:9999/dummy plugins: - name: echo config: # 设置响应状态码 status_code: 200 # 设置响应头,根据你的文件类型选择Content-Type headers: Content-Type: "application/yaml" # 如果是JSON就改成application/json # 这里直接写入你的OAS内容,用|保留格式和换行 body: | openapi: 3.0.3 info: title: My API Documentation version: 1.0.0 description: This is the static OAS documentation for our services paths: /service1/sample-path: get: summary: Fetch sample data responses: '200': description: Successful response content: application/json: schema: type: object properties: data: type: string routes: - name: service1 methods: - GET paths: - /service1/sample-path strip_path: true # 新增的OAS路由 - name: oas-route service: oas-static-service methods: - GET paths: - /oas strip_path: true
方案2:使用response-transformer插件
如果你已经熟悉response-transformer插件,也可以用它来替换dummy服务的响应内容,实现同样的效果:
_format_version: "2.1" _transform: true services: - name: service1 url: http://service1:port/sample-path - name: oas-static-service url: http://localhost:9999/dummy plugins: - name: response-transformer config: # 替换响应状态码 status_code: 200 # 替换响应头和响应体 replace: headers: Content-Type: "application/yaml" body: | openapi: 3.0.3 info: title: My API Documentation version: 1.0.0 # 移除可能干扰的默认响应头 remove: headers: - "Transfer-Encoding" routes: - name: service1 methods: - GET paths: - /service1/sample-path strip_path: true - name: oas-route service: oas-static-service methods: - GET paths: - /oas strip_path: true
关键注意事项
- 内容格式:如果你的OAS内容较长,一定要用
|来包裹响应体,这样能保留YAML/JSON的原有缩进和换行格式。 - Content-Type设置:根据你的文件类型正确设置响应头,YAML用
application/yaml或text/yaml,JSON用application/json,这样客户端才能正确解析内容。 - Dummy服务地址:不需要配置真实可访问的后端地址,因为插件会在请求转发前就返回静态响应,无效地址完全不影响功能。
内容的提问来源于stack exchange,提问作者Amin Ba
相关产品推荐
相关产品推荐

