struct Response
pub struct Response {
pub status int
pub message string
pub payload string
}用途
Grpc 服务端响应结果,包含状态码、响应头与正文数据。
公开字段
statusint- 字段(int)
messagestring- 字段(string)
payloadstring- 字段(string)
#github.com/xulang-org/packages/grpc扩展包 `grpc #github.com/xulang-org/packages/grpc`,由模块 github.com/xulang-org/packages 提供。
github.com/xulang-org/packages · 1.17.2 · 安装与使用
以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。
46_standalone_grpc/main.xu@main
grpc #github.com/xulang-org/packages/grpc
#errors
#strings
fn verify_protobuf_encoding() {
println("--- 1. Testing Protocol Buffers & gRPC Message Framing ---")
// 1. Varint test
v1 := grpc.encode_varint(300)
decoded_v1 := grpc.decode_varint(&v1, 0)
if decoded_v1 == 300 {
println(" [PASS] Varint encode/decode matched: 300")
} else {
println(" [FAIL] Varint mismatch: " + str(decoded_v1))
}
// 2. Protobuf String & Int fields
f_str := grpc.encode_string_field(1, "hello grpc")
f_int := grpc.encode_int_field(2, 42)
proto_msg := f_str + f_int
println(" [PASS] Protobuf serialized message length: " + str(proto_msg.len) + " bytes")
// 3. gRPC 5-byte Framing
grpc_frame := grpc.build_grpc_message(proto_msg + "")
if grpc_frame.len == proto_msg.len + 5 {
println(" [PASS] gRPC 5-byte header prefixed successfully (total: " + str(grpc_frame.len) + " bytes)")
} else {
println(" [FAIL] gRPC frame length mismatch")
}
parsed_payload := grpc.parse_grpc_message(grpc_frame + "")
if parsed_payload == proto_msg {
println(" [PASS] gRPC payload parsed & unpacked cleanly.")
} else {
println(" [FAIL] Unpacked payload mismatch!")
}
// 4. Protobuf Field Extraction
extracted_str := grpc.get_string_field(parsed_payload + "", 1)
extracted_int := grpc.get_int_field(parsed_payload + "", 2)
if extracted_str == "hello grpc" && extracted_int == 42 {
println(" [PASS] Protobuf field extraction: str='" + extracted_str + "', int=" + str(extracted_int))
} else {
println(" [FAIL] Protobuf field extraction mismatch")
}
}
fn verify_grpc_pool() {
println("\n--- 2. Testing gRPC Connection Pool ---")
$p := grpc.open_pool("127.0.0.1:9000", 5)
// 1. Connection Reuse
fd1 := p.get_conn()
println(" Borrow 1 fd: " + str(fd1))
p.put_conn(fd1)
fd2 := p.get_conn()
println(" Borrow 2 (after return) fd: " + str(fd2))
if fd1 == fd2 {
println(" [PASS] Connection reused successfully (fd " + str(fd1) + " == " + str(fd2) + ")")
} else {
println(" [WARN] Different fd allocated: " + str(fd1) + " vs " + str(fd2))
}
// 2. Multi-connection concurrent borrow
fd3 := p.get_conn()
println(" Borrow 3 (concurrently) fd: " + str(fd3))
if fd2 != fd3 {
println(" [PASS] Concurrently allocated distinct fds (" + str(fd2) + " != " + str(fd3) + ")")
} else {
println(" [FAIL] Expected distinct fds for concurrent connections!")
}
p.put_conn(fd2)
p.put_conn(fd3)
p.close()
println(" [PASS] gRPC Pool closed cleanly.")
}
fn verify_grpc_unary_call() {
println("\n--- 3. Testing gRPC Unary RPC Call ---")
$p := grpc.open_pool("127.0.0.1:9000", 5)
// DummyUnary accepts an empty or arbitrary message and echoes dummy response
req_body := grpc.encode_string_field(1, "Xu Language gRPC test")
resp := p.call_unary("/grpcbin.GRPCBin/DummyUnary", req_body) >>> (err) {
println(" [FAIL] gRPC call failed: " + err.msg())
p.close()
<<
}
println(" [PASS] gRPC Unary RPC Call (DummyUnary) succeeded!")
println(" Response payload length: " + str(resp.payload.len) + " bytes")
println(" Status: " + str(resp.status))
// Call SayHello on hello.HelloService
hello_req := grpc.encode_string_field(1, "Antigravity")
hello_resp := p.call_unary("/hello.HelloService/SayHello", hello_req) >>> (err) {
println(" [FAIL] SayHello failed: " + err.msg())
p.close()
<<
}
reply_msg := grpc.get_string_field(hello_resp.payload + "", 1)
if reply_msg == "hello Antigravity" {
println(" [PASS] gRPC Unary RPC Call (SayHello) succeeded!")
println(" [PASS] Echoed reply matched exactly: '" + reply_msg + "'")
} else {
println(" [FAIL] Echoed reply unexpected: '" + reply_msg + "'")
}
p.close()
}
fn main() {
println("=== Xu gRPC & HTTP/2 Native Driver Verification ===\n")
verify_protobuf_encoding()
verify_grpc_pool()
verify_grpc_unary_call()
println("\n[GRPC VERIFICATION 100% COMPLETED]")
}struct Responsepub struct Response {
pub status int
pub message string
pub payload string
}Grpc 服务端响应结果,包含状态码、响应头与正文数据。
status intmessage stringpayload stringstruct GrpcClientpub struct GrpcClient {
pub host string
pub port int
pub secure bool
}Grpc 客户端会话实例,维护与服务端的连接并提供操作接口。
host stringport intsecure boolnew_clientpub fn new_client(endpoint string) GrpcClient构造 client。
endpoint stringGrpcClient — 该类型的值
(GrpcClient) read_h2_framepub fn (c GrpcClient) read_h2_frame(fd int) H2FrameGrpcClient 上的操作:执行 read h2 frame 操作。失败时抛出错误,调用方需处理或继续传播。
c GrpcClientGrpcClient 实例;按值接收。fd intH2Frame — 该类型的值
(GrpcClient) connectpub fn (c GrpcClient) connect() int建立与目标服务端点的网络通信连接。失败时抛出错误,调用方需处理或继续传播。
c GrpcClientGrpcClient 实例;按值接收。int — 该类型的值
(GrpcClient) call_unarypub fn (c GrpcClient) call_unary(path string, req_bytes string) ResponseGrpcClient 上的操作:执行 call unary 操作。失败时抛出错误,调用方需处理或继续传播。
c GrpcClientGrpcClient 实例;按值接收。path stringreq_bytes stringResponse — 该类型的值
(GrpcClient) call_unary_on_fdpub fn (c GrpcClient) call_unary_on_fd(fd int, path string, req_bytes string, stream_id int) ResponseGrpcClient 上的操作:执行 call unary on fd 操作。失败时抛出错误,调用方需处理或继续传播。
c GrpcClientGrpcClient 实例;按值接收。fd intpath stringreq_bytes stringstream_id intResponse — 该类型的值
const H2_CLIENT_PREFACEpub const H2_CLIENT_PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"常量 H2_CLIENT_PREFACE,定义了相关的协议或算法配置参数。
const FRAME_DATApub const FRAME_DATA = 0常量 FRAME_DATA,定义了相关的协议或算法配置参数。
const FRAME_HEADERSpub const FRAME_HEADERS = 1常量 FRAME_HEADERS,定义了相关的协议或算法配置参数。
const FRAME_PRIORITYpub const FRAME_PRIORITY = 2常量 FRAME_PRIORITY,定义了相关的协议或算法配置参数。
const FRAME_RST_STREAMpub const FRAME_RST_STREAM = 3常量 FRAME_RST_STREAM,定义了相关的协议或算法配置参数。
const FRAME_SETTINGSpub const FRAME_SETTINGS = 4常量 FRAME_SETTINGS,定义了相关的协议或算法配置参数。
const FRAME_PUSH_PROMISEpub const FRAME_PUSH_PROMISE = 5常量 FRAME_PUSH_PROMISE,定义了相关的协议或算法配置参数。
const FRAME_PINGpub const FRAME_PING = 6常量 FRAME_PING,定义了相关的协议或算法配置参数。
const FRAME_GOAWAYpub const FRAME_GOAWAY = 7常量 FRAME_GOAWAY,定义了相关的协议或算法配置参数。
const FRAME_WINDOW_UPDATEpub const FRAME_WINDOW_UPDATE = 8常量 FRAME_WINDOW_UPDATE,定义了相关的协议或算法配置参数。
const FRAME_CONTINUATIONpub const FRAME_CONTINUATION = 9常量 FRAME_CONTINUATION,定义了相关的协议或算法配置参数。
const FLAG_ACKpub const FLAG_ACK = 1常量 FLAG_ACK,定义了相关的协议或算法配置参数。
const FLAG_END_STREAMpub const FLAG_END_STREAM = 1常量 FLAG_END_STREAM,定义了相关的协议或算法配置参数。
const FLAG_END_HEADERSpub const FLAG_END_HEADERS = 4常量 FLAG_END_HEADERS,定义了相关的协议或算法配置参数。
const FLAG_PADDEDpub const FLAG_PADDED = 8常量 FLAG_PADDED,定义了相关的协议或算法配置参数。
const FLAG_PRIORITYpub const FLAG_PRIORITY = 32常量 FLAG_PRIORITY,定义了相关的协议或算法配置参数。
struct H2Framepub struct H2Frame {
pub length int
pub frame_type int
pub flags int
pub stream_id int
pub payload string
}Grpc 协议数据帧结构封装。
length intframe_type intflags intstream_id intpayload stringencode_h2_headerpub fn encode_h2_header(len int, frame_type int, flags int, stream_id int) string编码 h2 header 数据。
len intframe_type intflags intstream_id intstring — 结果字符串
build_settings_framepub fn build_settings_frame(ack bool) string执行 build settings frame 操作。
ack boolstring — 结果字符串
build_data_framepub fn build_data_frame(stream_id int, data string, end_stream bool) string执行 build data frame 操作。
stream_id intdata stringend_stream boolstring — 结果字符串
build_grpc_hpack_headerspub fn build_grpc_hpack_headers(path string) string执行 build grpc hpack headers 操作。
path stringstring — 结果字符串
build_grpc_headers_for_host_schemepub fn build_grpc_headers_for_host_scheme(path string, authority string, scheme string) string执行 build grpc headers for host scheme 操作。
path stringauthority stringscheme stringstring — 结果字符串
build_headers_framepub fn build_headers_frame(stream_id int, path string, end_stream bool) string执行 build headers frame 操作。
stream_id intpath stringend_stream boolstring — 结果字符串
struct Poolpub struct Pool {
pub client GrpcClient
pub idle chan int
pub max_idle int
}Grpc 连接池管理器,并发安全地维护和调度复用套接字连接。
client GrpcClientidle chan intmax_idle intnew_poolpub fn new_pool(endpoint string, max_idle int) Pool构造 pool。
endpoint stringmax_idle intPool — 该类型的值
open_poolpub fn open_pool(endpoint string, max_idle int) Pool执行 open pool 操作。
endpoint stringmax_idle intPool — 该类型的值
(&Pool) get_connpub fn (p &Pool) get_conn() int&Pool 上的操作:读取 conn。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。int — 该类型的值
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)&Pool 上的操作:执行 put conn 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。fd int不返回值。
(&Pool) call_unarypub fn (p &Pool) call_unary(path string, req_bytes string) Response&Pool 上的操作:执行 call unary 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。path stringreq_bytes stringResponse — 该类型的值
(&Pool) closepub fn (p &Pool) close()&Pool 上的操作:关闭资源。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。不返回值。
const WIRE_VARINTpub const WIRE_VARINT = 0常量 WIRE_VARINT,定义了相关的协议或算法配置参数。
const WIRE_FIXED64pub const WIRE_FIXED64 = 1常量 WIRE_FIXED64,定义了相关的协议或算法配置参数。
const WIRE_LENGTH_DELIMITEDpub const WIRE_LENGTH_DELIMITED = 2常量 WIRE_LENGTH_DELIMITED,定义了相关的协议或算法配置参数。
const WIRE_FIXED32pub const WIRE_FIXED32 = 5常量 WIRE_FIXED32,定义了相关的协议或算法配置参数。
encode_varintpub fn encode_varint(val int) string编码 varint 数据。
val intstring — 结果字符串
struct VarintResultpub struct VarintResult {
pub value int
pub bytes_read int
}承载 value、bytes_read 等属性的结构体。
value intbytes_read intdecode_varint_fullpub fn decode_varint_full(buf &string, pos int) VarintResult解码 varint full 数据。
buf &stringpos intVarintResult — 该类型的值
decode_varintpub fn decode_varint(buf &string, pos int) int解码 varint 数据。
buf &stringpos intint — 该类型的值
encode_tagpub fn encode_tag(field_num int, wire_type int) string编码 tag 数据。
field_num intwire_type intstring — 结果字符串
encode_string_fieldpub fn encode_string_field(field_num int, val string) string编码 string field 数据。
field_num intval stringstring — 结果字符串
encode_int_fieldpub fn encode_int_field(field_num int, val int) string编码 int field 数据。
field_num intval intstring — 结果字符串
build_grpc_messagepub fn build_grpc_message(payload string) string执行 build grpc message 操作。
payload stringstring — 结果字符串
parse_grpc_messagepub fn parse_grpc_message(raw string) string解析为 grpc message。
raw stringstring — 结果字符串
decode_grpc_messagepub fn decode_grpc_message(raw string) string解码 grpc message 数据。失败时抛出错误,调用方需处理或继续传播。
raw stringstring — 结果字符串
get_string_fieldpub fn get_string_field(payload string, target_field int) string读取 string field。
payload stringtarget_field intstring — 结果字符串
get_int_fieldpub fn get_int_field(payload string, target_field int) int读取 int field。
payload stringtarget_field intint — 该类型的值