-
Notifications
You must be signed in to change notification settings - Fork 65
/
main.go
67 lines (53 loc) · 1.03 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"encoding/gob"
"fmt"
"net"
"time"
"github.com/ankur-anand/simple-go-rpc/src/client"
"github.com/ankur-anand/simple-go-rpc/src/server"
)
type User struct {
Name string
Age int
}
var userDB = map[int]User{
1: User{"Ankur", 85},
9: User{"Anand", 25},
8: User{"Ankur Anand", 27},
}
func QueryUser(id int) (User, error) {
if u, ok := userDB[id]; ok {
return u, nil
}
return User{}, fmt.Errorf("id %d not in user db", id)
}
func main() {
// new Type needs to be registered
gob.Register(User{})
addr := "localhost:3212"
srv := server.NewServer(addr)
// start server
srv.Register("QueryUser", QueryUser)
go srv.Run()
// wait for server to start.
time.Sleep(1 * time.Second)
// start client
conn, err := net.Dial("tcp", addr)
if err != nil {
panic(err)
}
cli := client.NewClient(conn)
var Query func(int) (User, error)
cli.CallRPC("QueryUser", &Query)
u, err := Query(1)
if err != nil {
panic(err)
}
fmt.Println(u)
u2, err := Query(8)
if err != nil {
panic(err)
}
fmt.Println(u2)
}