【问题标题】:No response from gorilla/rpc JSON RPC Servicegorilla/rpc JSON RPC 服务没有响应
【发布时间】:2013-07-01 09:23:43
【问题描述】:

我正在研究使用 gorilla web toolkit 创建一个简单的 RPC API。我正在使用他们文档中的示例,我正在 Chrome 中使用 Advanced Rest Client 进行测试并使用

http://localhost:1111/api/ 

并发布以下 RAW JSON 有效负载:

{"method":"HelloService.Say","params":[{"Who":"Test"}]}

这到达了服务器,我在记录它时就知道了(见下面的代码),我得到了 200 OK 响应。但是我得到“响应不包含任何数据”

我期待在下面的 Say 方法中定义的 JSON 回复消息。有人对问题所在有任何建议吗?

package main

import (
    "gorilla/mux"
    "gorilla/rpc"
    "gorilla/rpc/json"
    "log"
    "net/http"
)  

type HelloArgs struct {
    Who string
}

type HelloReply struct {
    Message string
}

type HelloService struct{}

func (h *HelloService) Say(r *http.Request, args *HelloArgs, reply *HelloReply) error {
    log.Printf(args.Who)
    reply.Message = "Hello, " + args.Who + "!"
    log.Printf(reply.Message)
    return nil
}

func main() {
    r := mux.NewRouter()    
    jsonRPC := rpc.NewServer()
    jsonCodec := json.NewCodec()
    jsonRPC.RegisterCodec(jsonCodec, "application/json")
    jsonRPC.RegisterCodec(jsonCodec, "application/json; charset=UTF-8") // For firefox 11 and other browsers which append the charset=UTF-8
    jsonRPC.RegisterService(new(HelloService), "")
    r.Handle("/api/", jsonRPC)  
    http.ListenAndServe(":1111", r)
}

【问题讨论】:

  • 1.缩进你的代码 2. 检查返回的错误 3. 再试一次
  • 你有没有让这个工作?

标签: go rpc mux


【解决方案1】:

因为gorilla/rpc/json实现了JSON-RPC,请求中需要三个参数:methodparamsid

在 JSON-RPC 中没有 id 的请求称为通知并且没有响应。

查看specification了解更多详情。

因此,在您的情况下,您需要使用以下 JSON:

{"method":"HelloService.Say","params":[{"Who":"Test"}], "id":"1"}

【讨论】:

  • 即使我们错过了id,我们也会得到200 OK,但是body中没有JSON。感谢您的回答。 :)
猜你喜欢
  • 2012-10-02
  • 2014-09-24
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多