feat: 添加 []byte ↔ bytes 支持(base64 透明编解码)

- Python 侧:_decode_bytes_args 根据函数注解自动解码入参,_bytes_encode 自动编码 bytes 返回值
- _cast 支持 bytes 类型(call_go[bytes] 返回值解码)
- 流式输出同步支持 chan []byte(每个 chunk 独立编解码)
- example/worker.py 新增 bytes_reverse / bytes_concat / bytes_chunks 示例
- example/main.go 新增对应演示用例
- README 补充类型表 []byte 行及完整使用章节
This commit is contained in:
2026-05-19 20:07:31 +08:00
parent e6a61cc1ee
commit 57775a33ec
4 changed files with 128 additions and 2 deletions

View File

@@ -269,6 +269,57 @@ gobridge.Invoke(ctx, sessB, "increment", 99) // worker 0: counter = 99独立
| 携带方式 | 替换 `pool` 参数 | 写入 `ctx` |
| 超时支持 | `context.WithTimeout(ctx, d)` 正常使用 | 同左 |
## []byte ↔ bytes 支持
Go 的 `[]byte` 通过 **base64** 编码在 JSON 帧中传输,框架在 Python 侧自动完成编解码,用户侧完全透明。
### Python 侧
函数参数注解为 `bytes` 时,框架自动将 Go 传入的 base64 字符串解码为 `bytes`
返回值为 `bytes` 时,框架自动将其编码为 base64 字符串再发送给 Go。
```python
from gobridge import expose
from typing import Iterator
@expose
def bytes_reverse(data: bytes) -> bytes:
return data[::-1]
@expose
def bytes_concat(a: bytes, b: bytes) -> bytes:
return a + b
# 流式输出 bytes对应 Go Invoke[chan []byte]
@expose
def bytes_chunks(data: bytes, size: int) -> Iterator[bytes]:
for i in range(0, len(data), size):
yield data[i:i + size]
```
### Go 侧
Go 直接使用 `[]byte``encoding/json` 自动处理 base64 编解码:
```go
// 普通 []byte 参数与返回值
rev, err := gobridge.Invoke[[]byte](ctx, pool, "bytes_reverse", []byte("hello"))
fmt.Printf("%s\n", rev) // olleh
cat, err := gobridge.Invoke[[]byte](ctx, pool, "bytes_concat", []byte("foo"), []byte("bar"))
fmt.Printf("%s\n", cat) // foobar
// 流式输出 []byte
ch, err := gobridge.Invoke[chan []byte](ctx, pool, "bytes_chunks", []byte("abcdefgh"), 3)
for chunk := range ch {
fmt.Printf("%s ", chunk) // abc def gh
}
```
> **效率说明**base64 编码约使数据体积增大 33%,并有少量 CPU 开销。
> 对于小块二进制数据(< 1 MB的 RPC 调用,这通常可以忽略不计;
> 若需传输大量原始二进制流,建议改用独立的 socket/文件通道。
## 注意事项
### 在 handler 中使用 `threading.Thread`
@@ -540,10 +591,13 @@ gobridge/
| `float64` | `float` |
| `string` | `str` |
| `bool` | `bool` |
| `[]byte` | `bytes` |
| `struct` | `dict` |
| `[]T` | `list` |
| `chan T` | `Iterator[T]` |
> `[]byte` 经 base64 编码在 JSON 帧中传输,框架自动完成编解码,用户侧透明。`chan T` 中的 `T` 同样支持 `[]byte`,即 `chan []byte` ↔ `Iterator[bytes]`。
## 参考
本项目的进程池、UDS 通信、帧协议设计参考自 [pyproc](https://github.com/YuminosukeSato/pyproc),在此基础上增加了 Go channel 与 Python yield 的流式对接及 ctx 取消支持。