API Gateway

API Gateway

AtlasX API Gateway ใช้ Ocelot ร่วมกับ .NET 8 เพื่อใช้เป็น Middleware สำหรับ Reroute API request ของคุณไปหา Microservice ต่างๆ บน Server

คุณสามารถตั้งค่าการ Reroute ของ Ocelot ได้ผ่านไฟล์ Configurations/APIGateway/ocelot-[Environment].json (ocelot.json สำหรับ Production) โดยตัวอย่างของไฟล์ config สามารถแสดงได้ดังนี้

{
  "$schema": "https://json.schemastore.org/ocelot.json",
  "Routes": [
    {
      "UpstreamHttpMethod": [],
      "UpstreamPathTemplate": "/api-gateway/{everything}",
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5000
        }
      ],
      "DangerousAcceptAnyServerCertificateValidator": true
    }
  ]
}

การตั้งค่า Route

คุณสามารถทำการเพิ่ม Route ต่างๆ สำหรับ redirect request ของคุณไปยัง Microservice ที่แตกต่างกันได้ใน Array Routes โดย property ที่คุณต้องระบุมีดังนี้

  • UpstreamHttpMethod : ระบุ HTTP Method ที่อนุญาตให้ reroute เช่น [ “POST”, “PUT”, “GET” ] เป็นต้น (หรือปล่อยเป็น Array ว่าง ถ้า allow ทุก method)
  • UpstreamPathTemplate : ระบุ template ของ URL path ขาเข้า (ตัวอย่าง /api-gateway/{everything} จะรับ Request จาก http://{gateway-host}/api-gateway/{everything} เป็นต้น)
  • DownstreamPathTemplate : ระบุ template ของ URL path ขาออกไปยัง Microservice ปลายทาง (ตัวอย่าง /{everything} จะ redirect ที่มาจาก http://{gateway-host}/api-gateway/{everything} ส่งต่อไปยัง http://{backend-host}/{everything} เป็นต้น)
  • DownstreamScheme : ระบุ Protocal ของ Backend (http หรือ https เป็นต้น)
  • DownstreamHostAndPorts : ระบุ Host และ Port ของ Backend ที่จะ Redirect ไป เช่น { “Host”: “localhost”, “Port”: 5000 } จะ redirect ไปหา Backend ที่ http://localhost:5000 เป็นต้น
  • DangerousAcceptAnyServerCertificateValidator : หากตั้งเป็น true จะทำให้ API Gateway ไม่สนใจ SSL Certificate ของ Request ที่เข้ามา (ไม่แนะนำให้ใช้บน Production)

สำหรับการตั้งค่าอื่นๆ สามารถดูเพิ่มเติมได้ที่ Ocelot Gateway Configuration