【问题标题】:Batch JSON-RPCs in Go with Gorilla RPC使用 Gorilla RPC 在 Go 中批处理 JSON-RPC
【发布时间】:2014-09-24 02:52:41
【问题描述】:

好的,我正在使用服务器。它提供网页并提供其他服务。

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/rpc"
    "github.com/gorilla/rpc/json"
)

type Service struct {
    Name string
}

type ServiceArgs struct {
    Str string
    Val float64
}

type ServiceReply struct {
    Message string
}

func (e *Service) DoSomething(request *http.Request, args *ServiceArgs, reply *ServiceReply) error {
    fmt.Println("DoSomething called remotely!")
    reply.Message = "OMG. It works."

    return nil
}

func main() {
    rpcHandler := rpc.NewServer()
    rpcHandler.RegisterCodec(json.NewCodec(), "application/json")
    rpcHandler.RegisterService(new(Service), "")
    http.Handle("/rpc", rpcHandler)

    http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("."))))

    fmt.Println("Listening on port 8080.")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatalln(err)
    }
}

我在服务器端有一个 API,我希望普通客户端能够访问它。为此,我开始学习更多关于 JSON-RPC 的知识。这就是我从网络浏览器调用Service.DoSomething 的方式。

var log = document.getElementById("log");
var request = new XMLHttpRequest();

var command = {
    "jsonrpc":"2.0",
    "method":"Service.DoSomething",
    "params":[{
        "Str":"pie",
        "Val":3.14
    }],
    "id":1
};

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        var response = JSON.parse(request.responseText).result;
        log.textContent += response["Message"];
    } else {
        console.log(request.statusText);
    }
};

request.open("POST", "/rpc", true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(JSON.stringify(command));

这很好用。我看到“OMG。它有效。”当我运行该 JavaScript 时,在我的浏览器中。接下来,我想运行多个方法调用。我发现有一种方法可以向服务器发送“批量”调用。所以我从 JavaScript 中尝试了这个。

var command = [
    {"jsonrpc":"2.0","method":"Service.DoSomething","params":[{"Str":"pie","Val":3.14}],"id":1},
    {"jsonrpc":"2.0","method":"Service.DoSomething","params":[{"Str":"pie","Val":3.14}],"id":2}
];

request.send(JSON.stringify(command));

但是,这给了我一个400 (Bad Request)。我在某处搞砸了语法吗?或者这是gorilla/rpc 的问题?

【问题讨论】:

  • 如果你得到415 (Unsupported Media Type),确保你有rpcHandler.RegisterCodec(json.NewCodec(), "application/json") AND request.setRequestHeader("Content-Type", "application/json");
  • 您从哪里了解到批处理调用的?

标签: json go rpc


【解决方案1】:

根据The Gorilla Toolkit JSON-RPC overview

此包遵循 JSON-RPC 1.0 规范:

根据The JSON-RPC specthe JSON-RPC Google group discussion,'batch' 是 JSON-RPC 2.0 功能。

看起来 Gorilla JSON-RPC 不理解批处理查询。

【讨论】:

    猜你喜欢
    • 2012-10-02
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 2012-02-13
    • 2012-08-15
    相关资源
    最近更新 更多