【发布时间】: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")ANDrequest.setRequestHeader("Content-Type", "application/json");。 -
您从哪里了解到批处理调用的?