文件

快速開始

在具備 Redis 與目標語言 runtime 的主機上安裝、設定並啟動 go-faas。

前置需求

macOS 可用 sandbox-exec 做開發用執行;生產沙箱以 Linux 為目標。

安裝

從原始碼

git clone https://github.com/pardnchiu/go-faas.git
cd go-faas
go build -o go-faas cmd/api/main.go

使用 go install

go install github.com/pardnchiu/go-faas/cmd/api@latest

安裝 TypeScript 相依

npm install

首次啟動時,程式會檢查 bwrapnodepython3 等相依;若缺失,會嘗試透過系統套件管理器安裝(僅 Linux)。

設定

複製 .env.example 並填入值(或於 shell 匯出相同變數):

cp .env.example .env
變數 必要 預設值 說明
HTTP_PORT 8080 HTTP 服務埠號
MAX_CPUS 1 沙箱 CPU 配額(核心數)
MAX_MEMORY 128M 沙箱記憶體上限
CODE_MAX_SIZE 262144(256KB) 允許的最大程式碼位元組數
TIMEOUT_SCRIPT 30 腳本執行逾時(秒)
REDIS_HOST localhost Redis 主機
REDIS_PORT 6379 Redis 埠號
REDIS_PASSWORD Redis 密碼
REDIS_DB 0 Redis 資料庫編號
REDIS_TIMEOUT_SECONDS 5 Redis 連線逾時(秒)

詳見 設定

啟動伺服器

./go-faas

cmd/api/main.go 啟動順序:

  1. godotenv 載入 .env(失敗則改用系統環境變數)
  2. checker.CheckPackage() 檢查 runtime
  3. database.Init()(Redis ping)
  4. sandbox.NewSlice()(Linux systemd user slice)
  5. 監聽 HTTP_PORT

基礎:上傳腳本

curl -X POST http://localhost:8080/upload \
  -H "Content-Type: application/json" \
  -d '{
    "path": "math/add",
    "language": "python",
    "code": "return event.get(\"a\", 0) + event.get(\"b\", 0)"
  }'

回應:

{
  "path": "math/add",
  "language": "python",
  "version": 1739000000
}

基礎:執行已儲存腳本

最新版本:

curl -X POST http://localhost:8080/run/math/add \
  -H "Content-Type: application/json" \
  -d '{
    "input": "{\"a\": 3, \"b\": 5}"
  }'

指定版本:

curl -X POST "http://localhost:8080/run/math/add?version=1739000000" \
  -H "Content-Type: application/json" \
  -d '{
    "input": "{\"a\": 3, \"b\": 5}"
  }'

回應:

{
  "data": 8,
  "type": "number"
}

進階:立即執行(Run-Now)

curl -X POST http://localhost:8080/run-now \
  -H "Content-Type: application/json" \
  -d '{
    "language": "javascript",
    "code": "return { sum: event.a + event.b }",
    "input": "{\"a\": 10, \"b\": 20}"
  }'

進階:SSE 串流

curl -X POST http://localhost:8080/run-now \
  -H "Content-Type: application/json" \
  -d '{
    "language": "python",
    "code": "import time\nfor i in range(5):\n    print(i)\n    time.sleep(0.5)\nreturn \"done\"",
    "input": "{}",
    "stream": true
  }'

串流格式:

data: {"event":"log","data":"0","type":"text"}

data: {"event":"log","data":"1","type":"text"}

data: {"event":"result","data":"done","type":"string"}

下一步

EN