
Go 标准库的 net/rpc/jsonrpc 默认不支持 HTTP 协议,仅适用于裸 TCP 连接,因此直接用 curl 发送 HTTP 请求会失败;需手动封装 HTTP Handler,将请求体和响应流适配为 jsonrpc.ServerCodec 所需的 io.ReadWriter。
go 标准库的 `net/rpc/jsonrpc` 默认不支持 http 协议,仅适用于裸 tcp 连接,因此直接用 curl 发送 http 请求会失败;需手动封装 http handler,将请求体和响应流适配为 `jsonrpc.servercodec` 所需的 `io.readwriter`。
Go 的 net/rpc/jsonrpc 包设计初衷是用于底层 RPC 通信(如 TCP 连接),其 ServeCodec 方法期望一个实现了 io.ReadWriteCloser 的连接对象——而 HTTP 请求的 r.Body(只读)与 http.ResponseWriter(只写)无法直接满足该接口要求。因此,原生调用 curl 会返回 Empty reply from server(cURL 错误 52),因为服务端未正确写入响应或提前关闭了连接。
解决方法是构造一个轻量级的 HttpConn 适配器,桥接 HTTP 的输入/输出流:
type HttpConn struct {
in io.Reader
out io.Writer
}
func (c *HttpConn) Read(p []byte) (n int, err error) { return c.in.Read(p) }
func (c *HttpConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
func (c *HttpConn) Close() error { return nil }该结构体实现了 io.ReadWriteCloser 的最小契约(Close() 为空实现是安全的,因 HTTP 连接由 http.Server 管理)。随后,在 HTTP handler 中创建 jsonrpc.ServerCodec,并显式设置响应头与状态码:
http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/test" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
codec := jsonrpc.NewServerCodec(&HttpConn{in: r.Body, out: w})
if err := server.ServeRequest(codec); err != nil {
log.Printf("JSON-RPC request error: %v", err)
http.Error(w, "Internal RPC error", http.StatusInternalServerError)
}
}
}))⚠️ 注意事项:
- 方法名必须严格匹配:示例中 Go 方法名为 Greet,对应 curl 请求中的 "method": "Test.Greet"(格式为 StructName.MethodName);
- 参数字段名大小写敏感:Go 结构体字段 Name 对应 JSON 中的 "name"(遵循 Go 的 JSON tag 规则,默认小写首字母);
- 避免阻塞主 goroutine:http.Serve() 是阻塞调用,无需额外 for { <-ch } 循环;原代码中 startServer 的无限 Accept 循环已被 http.Serve 替代;
- 错误处理不可省略:ServeRequest 失败时需主动调用 http.Error 或写入错误响应,否则客户端可能挂起或收到空响应。
最终,使用以下 curl 命令即可成功调用:
curl -X POST \
-H "Content-Type: application/json" \
-d '{"id": 1, "method": "Test.Greet", "params": [{"name": "world"}]}' \
http://localhost:8080/test响应示例:
{"id":1,"result":"Hello world","error":null}总结:Go 原生 JSON-RPC 并非为 Web 场景设计,若需 HTTP 兼容性,应优先考虑成熟框架(如 gorilla/rpc、grpc-gateway)或升级至基于 HTTP/JSON 的轻量 API(如 net/http + encoding/json 手动路由)。但理解 HttpConn 适配模式,对深入掌握 Go I/O 抽象与协议桥接机制极具价值。


















