doulu8341 2017-12-24 17:28
浏览 122
已采纳

Go中基于HTTP的JSONRPC [重复]

This question already has an answer here:

How can I use JSON-RPC over HTTP based on this specification in Go?

Go provides JSON-RPC codec in net/rpc/jsonrpc but this codec use network connection as input so you cannot use it with go RPC HTTP handler. I attach sample code that uses TCP for JSON-RPC:

func main() {
    cal := new(Calculator)
    server := rpc.NewServer()
    server.Register(cal)
    listener, e := net.Listen("tcp", ":1234")
    if e != nil {
        log.Fatal("listen error:", e)
    }
    for {
        if conn, err := listener.Accept(); err != nil {
            log.Fatal("accept error: " + err.Error())
        } else {
            log.Printf("new connection established
")
            go server.ServeCodec(jsonrpc.NewServerCodec(conn))
        }
    }
}
</div>
  • 写回答

1条回答 默认 最新

  • ds3422222 2017-12-24 18:16
    关注

    The built-in RPC HTTP handler uses the gob codec on a hijacked HTTP connection. Here's how to do the same with the JSONRPC.

    Write an HTTP handler that runs the JSONRPC server with a hijacked connection.

    func serveJSONRPC(w http.ResponseWriter, req *http.Request) {
        if req.Method != "CONNECT" {
            http.Error(w, "method must be connect", 405)
            return
        }
        conn, _, err := w.(http.Hijacker).Hijack()
        if err != nil {
            http.Error(w, "internal server error", 500)
            return
        }
        defer conn.Close()
        io.WriteString(conn, "HTTP/1.0 Connected
    
    ")
        jsonrpc.ServeConn(conn)
    }
    

    Register this handler with the HTTP server. For example:

     http.HandleFunc("/rpcendpoint", serveJSONRPC)
    

    EDIT: OP has since updated question to make it clear that they want GET/POST instead of connect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办