本文详解如何使用 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 RPCpackage 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 JSONcurl 必须使用 POST 方法不是 CONNECT并发送符合 JSON-RPC 1.0 规范的请求体 幻导航网 发现优质实用网站,开启网络探索之旅