From 04a7596a83a8d319c2c99faef93fea106e0eecc8 Mon Sep 17 00:00:00 2001 From: qydysky Date: Sat, 1 Jul 2023 17:04:19 +0800 Subject: [PATCH] add --- rpc/Rpc.go | 19 ++++++++++++++++- rpc/Rpc_test.go | 56 +++++++++++++++++++++++++------------------------ 2 files changed, 47 insertions(+), 28 deletions(-) diff --git a/rpc/Rpc.go b/rpc/Rpc.go index a251d23..c69b10b 100644 --- a/rpc/Rpc.go +++ b/rpc/Rpc.go @@ -1,6 +1,8 @@ package part import ( + "bytes" + "encoding/gob" "net/http" "net/rpc" @@ -9,7 +11,22 @@ import ( type Gob struct { Key string - Data any + Data []byte +} + +func NewGob(k string) *Gob { + return &Gob{Key: k} +} + +func (t *Gob) Encode(e any) (err error) { + var buf bytes.Buffer + err = gob.NewEncoder(&buf).Encode(e) + t.Data = buf.Bytes() + return +} + +func (t *Gob) Decode(e any) (err error) { + return gob.NewDecoder(bytes.NewReader(t.Data)).Decode(e) } type DealGob struct { diff --git a/rpc/Rpc_test.go b/rpc/Rpc_test.go index 506351f..dadb0c6 100644 --- a/rpc/Rpc_test.go +++ b/rpc/Rpc_test.go @@ -2,6 +2,7 @@ package part import ( "errors" + "log" "testing" "time" ) @@ -9,17 +10,18 @@ import ( func TestMain(t *testing.T) { pob := Pob{Host: "127.0.0.1:10902", Path: "/123"} if shutdown, e := pob.Server(func(i, o *Gob) error { - if iv, ok := i.Data.(int); !ok { - return errors.New("iv") - } else { - switch i.Key { - case "+": - o.Data = iv + 1 - case "-": - o.Data = iv - 1 - default: - return errors.New("no key") + switch i.Key { + case "+": + var ivv int + if e := i.Decode(&ivv); e != nil { + log.Fatal("d", e) + } + ivv += 1 + if e := o.Encode(ivv); e != nil { + log.Fatal("e", e) } + default: + return errors.New("no key") } return nil }); e != nil { @@ -33,28 +35,28 @@ func TestMain(t *testing.T) { if c, e := pob.Client(); e != nil { t.Fatal(e) } else { - var gob = Gob{"+", 9} - if e := c.Call(&gob); e != nil { + var gob = NewGob("+") + + var i int = 9 + if e := gob.Encode(&i); e != nil { t.Fatal(e) - } else if gob.Key != "+" { - t.Fatal() - } else if i, ok := gob.Data.(int); !ok || i != 10 { - t.Fatal() } - c.Close() - } - - if c, e := pob.Client(); e != nil { - t.Fatal(e) - } else { - var gob = Gob{"-", 9} - if e := c.Call(&gob); e != nil { + if e := gob.Decode(&i); e != nil { t.Fatal(e) - } else if gob.Key != "-" { - t.Fatal() - } else if i, ok := gob.Data.(int); !ok || i != 8 { + } + if e := c.Call(gob); e != nil { + t.Fatal(e) + } else if gob.Key != "+" { t.Fatal() + } else { + if e := gob.Decode(&i); e != nil { + t.Fatal(e) + } + if i != 10 { + t.Fatal() + } } c.Close() } + } -- 2.39.2