質問

I'm investigating using the gorilla web toolkit to create a simple RPC API. I'm using the example from their documentation and I'm testing using Advanced Rest Client in Chrome and use

http://localhost:1111/api/ 

and POST the following RAW JSON payload:

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

This reaches the server, I know this as I'm logging it (see code below) and I get a 200 OK response. However I'm getting "Response does not contain any data"

I'm expecting the JSON reply message that is defined in the Say method below. Does anyone have any suggestions as to what the problem is?

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)
}
役に立ちましたか?

解決

It's because gorilla/rpc/json implements JSON-RPC, which requires three parameters in the request: method, params and id.

Requests without id in JSON-RPC are called notifications and do not have responses.

Check specification for more details.

So, in your case, you need to use following JSON:

{"method":"HelloService.Say","params":[{"Who":"Test"}], "id":"1"}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top