用curl调用golang调用jsonrpc

时间:2016-04-13 21:45:04

标签: http curl go json-rpc

我在golang上写的“hello world”rpc服务。它运行正常,并且jsonrpc客户端正在运行。但是我需要用curl发送请求,这个例子不起作用:

curl \
-X POST \
-H "Content-Type: application/json" \
-d '{"id": 1, "method": "Test.Say", "params": [{"greet": "world"}]}' \
http://localhost:1999/_goRPC_

接受连接,但绝对没有结果:

curl: (52) Empty reply from server 

这是我的代码:

package main

import (
  "log"
  "os"
  "time"
  "net"
  "net/rpc"
  "net/rpc/jsonrpc"
)

// RPC Api structure
type Test struct {}

// Greet method arguments
type GreetArgs struct {
  Name string
}

// Grret message accept object with single param Name
func (test *Test) Greet(args *GreetArgs, result *string) (error) {
  *result = "Hello " + args.Name
  return nil
}

// Start server with Test instance as a service
func startServer(ch chan<- bool, port string) {
  test := new(Test)

  server := rpc.NewServer()
  server.Register(test)

  listener, err := net.Listen("tcp", ":" + port)

  if err != nil {
      log.Fatal("listen error:", err)
  }

  defer listener.Close()

  for {
      conn, err := listener.Accept()

      if err != nil {
          log.Fatal(err)
      }

      go server.ServeCodec(jsonrpc.NewServerCodec(conn))
      ch <- true
  }
}

// Start client and call Test.Greet method
func startClient(port string) {
  conn, err := net.Dial("tcp", ":" + port)

  if err != nil {
      panic(err)
  }
  defer conn.Close()

  c := jsonrpc.NewClient(conn)

  var reply string
  var args = GreetArgs{"world"}
  err = c.Call("Test.Greet", args, &reply)
  if err != nil {
      log.Fatal("arith error:", err)
  }
  log.Println("Result: ", reply)
}

func main() {
  if len(os.Args) < 2 {
    log.Fatal("port not specified")
  }

  port := os.Args[1]
  ch := make(chan bool)

  go startServer(ch, port)
  time.Sleep(500 * time.Millisecond)
  go startClient(port)

  // Produce log message each time connection closes
  for {
    <-ch
    log.Println("Closed")
  }
}

2 个答案:

答案 0 :(得分:6)

jsonrpc包目前不支持HTTP上的json-rpc。所以,你不能用curl调用jsonrpc。如果你真的想这样做,你可以创建一个HTTP处理程序,使HTTP请求/响应适应ServerCodec。例如:

package main

import (
    "io"
    "log"
    "net"
    "net/http"
    "net/rpc"
    "net/rpc/jsonrpc"
    "os"
)

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 }

// RPC Api structure
type Test struct{}

// Greet method arguments
type GreetArgs struct {
    Name string
}

// Grret message accept object with single param Name
func (test *Test) Greet(args *GreetArgs, result *string) error {
    *result = "Hello " + args.Name
    return nil
}

// Start server with Test instance as a service
func startServer(port string) {
    test := new(Test)

    server := rpc.NewServer()
    server.Register(test)

    listener, err := net.Listen("tcp", ":"+port)

    if err != nil {
        log.Fatal("listen error:", err)
    }

    defer listener.Close()
    http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        if r.URL.Path == "/test" {
            serverCodec := jsonrpc.NewServerCodec(&HttpConn{in: r.Body, out: w})
            w.Header().Set("Content-type", "application/json")
            w.WriteHeader(200)
            err := server.ServeRequest(serverCodec)
            if err != nil {
                log.Printf("Error while serving JSON request: %v", err)
                http.Error(w, "Error while serving JSON request, details have been logged.", 500)
                return
            }
        }

    }))
}

func main() {
    if len(os.Args) < 2 {
        log.Fatal("port not specified")
    }

    port := os.Args[1]

    startServer(port)
}

现在您可以使用curl -X POST -H "Content-Type: application/json" -d '{"id": 1, "method": "Test.Greet", "params": [{"name":"world"}]}' http://localhost:port/test

来调用它

部分代码来自this post

答案 1 :(得分:4)

@jfly有一个很好的解决方案。

另一种选择,如果您仍然希望使用go jsonrpc cient(可能是最简单的选项)之外的其他内容进行测试,或者使用@jfly的答案,您可以使用telnet发送原始数据:

computer:~ User$ telnet 127.0.0.1 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"method":"Test.Greet","params":[{"Name":"world"}],"id":0}
{"id":0,"result":"Hello world","error":null}
{"method":"Test.Greet","params":[{"Name":"world"}],"id":0}
{"id":0,"result":"Hello world","error":null}
{"method":"Test.Greet","params":[{"Name":"world"}],"id":0}
{"id":0,"result":"Hello world","error":null}

以上是输出,包括我输入的有效负载和服务器的响应。

当我弄清楚要发送的正确有效负载时,tcpdump是我的朋友。