本文详解如何使用 curl 等通用 HTTP 工具跨语言调用 Go net/rpc 服务,重点基于 rpc/jsonrpc 实现的 JSON-RPC 1.0 协议,涵盖请求构造、序列化规则、常见错误及最佳实践。 本文详解如何使用 curl 等通用 http 工具跨语言调用 go `net/rpc` 服务,重点基于 `rpc/jsonrpc` 实现的 json-rpc 1.0 协议,涵盖请求构造、序列化规则、常见错误及最佳实践。Go 标准库的 net/rpc 默认采用自定义二进制协议(Gob),不兼容 HTTP 直接交互。若需通过 curl 或其他非 Go 客户端调用,必须启用 rpc/jsonrpc 子包提供的 JSON-RPC 1.0 支持------它将 RPC 请求/响应封装为标准 JSON 格式,并通过 HTTP POST(而非 CONNECT)传输。? 正确的服务端配置(关键前提)首先,服务端需显式注册 JSON-RPC 处理器,而非默认的 Gob RPC:package mainimport ( "log" "net/http" "net/rpc" "net/rpc/jsonrpc")type Args struct{ A, B int }type Quotient struct{ Quo, Rem int }type Arith intfunc (t *Arith) Multiply(args *Args, reply *int) error { *reply = args.A * args.B return nil}func main() { rpc.Register(new(Arith)) rpc.HandleHTTP() // 注册 /_goRPC 路由(用于 Gob) // ? 关键:为 JSON-RPC 单独注册处理器 http.Handle("/goRPC", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 设置 Content-Type 避免客户端解析失败 w.Header().Set("Content-Type", "application/json") jsonrpc.ServeHTTP(w, r) })) log.Println("RPC server listening on :1234") log.Fatal(http.ListenAndServe(":1234", nil))}?? 注意:/goRPC(末尾带下划线)是 Go jsonrpc 包约定的默认路径,不可省略或修改;而 /_goRPC(无下划线)仅用于 Gob 协议,curl 无法直接通信。? 正确的 curl 请求格式(POST + JSON)curl 必须使用 POST 方法(不是 CONNECT),并发送符合 JSON-RPC 1.0 规范的请求体: 幻导航网 发现优质实用网站,开启网络探索之旅!
相关推荐
ZHOU_WUYI13 小时前
4. light wam 模型loss计算过程井川廊咏13 小时前
vi 删除指定范围的行,不用再反复按 ddnwsuaf_huasir13 小时前
【无标题】长不胖的路人甲14 小时前
Serial 串行、Parallel 并行、CMS 并发收集器z落落14 小时前
StudentInfo表 分页、增删改 存储过程+C# WinForm 存储过程实现分页和增删改查影寂ldy14 小时前
WinForm 数据库【新增+编辑】完整功能(参数化查询+配置文件+防报错全套)迷枫71214 小时前
达梦数据库 Hint 使用与 Hint 注入实战Python私教15 小时前
Codex 写出的代码能跑却算错钱:我用 3 个测试拆穿一次 AI 编程幻觉Python私教15 小时前
我只写了一个 add 工具,终于把 MCP 的 Host、Client、Server 跑明白了小大宇15 小时前
python milvus 案例