2

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\n")
            go server.ServeCodec(jsonrpc.NewServerCodec(conn))
        }
    }
}
Parham Alvani
  • 2,305
  • 2
  • 14
  • 25

1 Answers1

1

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\r\n\r\n")
    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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • [JSON-RPC specification](http://www.jsonrpc.org/historical/json-rpc-over-http.html) mentioned that you must use GET or POST as HTTP method but I think it is not true in your way. – Parham Alvani Dec 24 '17 at 18:43
  • @ParhamAlvani Your question and comment on the question points to this solution. Update the question to say what you want. – Charlie Tumahai Dec 24 '17 at 19:04
  • Thanks, I have updated my question. but I think this solution is the best solution based on Go builtin libraries. – Parham Alvani Dec 24 '17 at 19:10