2014-08-01 00:32

使用Gorilla RPC进行批处理JSON-RPC


Okay, so I'm working a server. It serves webpages and provides other services.

package main

import (


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 {

I have an API on the server side that I want normal clients to be able to access. For this, I started learning more about JSON-RPC. This is how I call Service.DoSomething from a web browser.

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

var command = {

request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        var response = JSON.parse(request.responseText).result;
        log.textContent += response["Message"];
    } else {
};"POST", "/rpc", true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

This works fine. I see "OMG. It works." in my browser when I run that JavaScript. Next, I wanted to run multiple method calls. I found that there is a way to send a "batch" of calls to the server. So I tried this from JavaScript.

var command = [


However, this gives me a 400 (Bad Request). Did I screw up the syntax somewhere? Or is this a problem with gorilla/rpc?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答