first commit

This commit is contained in:
2026-04-10 09:24:28 +08:00
commit a92abca252
10 changed files with 1645 additions and 0 deletions

75
example/worker.py Normal file
View File

@@ -0,0 +1,75 @@
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "python"))
from gobridge import gobridge, run
from typing import Iterator
@gobridge
def add(a: int, b: int) -> int:
return a + b
@gobridge
def range_gen(start: int, stop: int) -> Iterator[int]:
"""流式输出:对应 Go 侧 Invoke[chan int]"""
for i in range(start, stop):
yield i
@gobridge
def sum_stream(numbers: Iterator[int]) -> int:
"""流式输入:对应 Go 侧传入 chan int 参数"""
return sum(numbers)
@gobridge
def double_stream(numbers: Iterator[int]) -> Iterator[int]:
"""双向流输入每个数yield 其平方,对应 Go 侧 Invoke[chan int](c, ctx, "double_stream", inputChan)"""
for n in numbers:
yield n * n
# ── structdict类型 ──────────────────────────────────────────────────────
@gobridge
def get_user(uid: int) -> dict:
"""普通调用:返回一个 structGo 对应 User"""
return {"id": uid, "name": f"user_{uid}", "score": uid * 1.5}
@gobridge
def total_score(users: list) -> float:
"""slice 输入:接收 []User返回总分"""
return sum(u["score"] for u in users)
@gobridge
def enrich_users(users: list) -> list:
"""slice 输入输出:为每个 user 追加 level 字段"""
result = []
for u in users:
u = dict(u)
u["level"] = "gold" if u["score"] >= 10 else "silver"
result.append(u)
return result
# ── struct/slice 流式组合 ────────────────────────────────────────────────────
@gobridge
def gen_users(count: int) -> Iterator[dict]:
"""流式输出 structyield 多个 User对应 Go 侧 Invoke[chan User]"""
for i in range(1, count + 1):
yield {"id": i, "name": f"user_{i}", "score": float(i * 3)}
@gobridge
def process_users(users: Iterator[dict]) -> Iterator[dict]:
"""双向流 struct输入流式 Useryield 处理后的 User"""
for u in users:
yield {"id": u["id"], "name": u["name"].upper(), "score": u["score"] * 2}
run()