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

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>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • 从网页访问golang http + jsonrpc 2个答案 \ r

    如何使用基于 Go中的此规范

    Go提供了JSON-RPC net / rpc / jsonrpc 中的编解码器,但是此编解码器使用网络连接作为输入,因此您不能将其与go RPC HTTP处理程序一起使用。 我附加了将TCP用于JSON-RPC的示例代码:

      func main(){
     cal:= new(Calculator)
    服务器:= rpc.NewServer()  
     server.Register(cal)
    侦听器,e:= net.Listen(“ tcp”,“:1234”)
    如果e!= nil {
     log.Fatal(“ listen error:”,e)  
    } 
    为{
    ,如果conn,err:= listener.Accept();  err!= nil {
     log.Fatal(“ accept error:” + err.Error())
    } else {
     log.Printf(“已建立新连接
    ”)
    转到server.ServeCodec(jsonrpc  .NewServerCodec(conn))
    } 
    } 
    } 
       
     
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 评论

相关推荐 更多相似问题