服务器端
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 客户端请求方式
golangjson
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)
}
}
}