Golang JSONRPC 2.0 范例:使用 gorilla/rpc/v2 实现

yufei       4 年 前       3294

服务器端

服务端还是比较清晰的,代码量也比较少,如果需要权限验证之类的,可以通过 r 获取参数来实现

package main

import (
    "github.com/gorilla/rpc/v2"
    "github.com/gorilla/rpc/v2/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 {
    reply.Message = "Hello, " + args.Who + "!"
    return nil
}

func main() {
    log.Printf("Starting RPC Server on :10000\n")
    s := rpc.NewServer()
    s.RegisterCodec(json.NewCodec(), "application/json")
    s.RegisterService(new(HelloService), "")
    http.Handle("/rpc", s)
    http.ListenAndServe("localhost:10000", nil)
}

CURL 请求方式

curl -X POST -H "Content-Type: application/json" \
-d '{"method":"HelloService.Say","params":[{"Who":"Test"}], "id":"1"}' \
http://localhost:10000/rpc

Golang 客户端请求方式

客户端就比较复杂了,主要是 golang 的原生自带的 json 导致的。

package main

import (
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "math/rand"
    "net/http"
    "strings"
    "time"
)

type HelloArgs struct {
    Who string
}

type HelloReply struct {
    Message string
}

type HelloResponse struct {
    Result HelloReply `json:"result"`
    Error  string     `json:"error"`
    Id     string     `json:"id"`
}

type HelloRequest struct {
    Method string      `json:"method"`
    Params []HelloArgs `json:"params"`
    Id     string      `json:"id"`
}

func init() {
    rand.Seed(time.Now().UnixNano())
}

func (h *HelloRequest) Say(p HelloArgs) *HelloRequest {
    h.Method = "HelloService.Say"
    h.Params = []HelloArgs{p}
    h.Id = fmt.Sprintf("%v.%v", time.Now().UnixNano(), rand.Int63())
    return h
}

func main() {

    log.Printf("Calling RPC Server on :10000\n")
    r := &HelloRequest{}
    if b, err := json.Marshal(r.Say(HelloArgs{flag.Arg(0)})); err != nil {
        log.Fatal(err)
    } else {
        log.Printf("json %s", b)
        if res, err := http.Post("http://localhost:10000/rpc", "application/json", strings.NewReader(string(b))); err != nil {
            log.Fatal(err)
        } else {
            log.Printf("res : %v", res)
            hello, err := ioutil.ReadAll(res.Body)
            res.Body.Close()
            if err != nil {
                log.Fatal(err)
            }
            log.Printf("raw %s", hello)
            var data HelloResponse
            if err := json.Unmarshal(hello, &data); err != nil {
                log.Fatal(err)
            }
            log.Printf("parsed %+v", data)
        }
    }
}
目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.