-
Notifications
You must be signed in to change notification settings - Fork 11
/
hello.go
77 lines (61 loc) · 1.5 KB
/
hello.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
68
69
70
71
72
73
74
75
76
77
// Copyright 2018 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"fmt"
"io/ioutil"
"log"
"mime"
"net"
"net/rpc"
"github.com/chai2010/pbgo/examples/hello.pb"
)
type HelloService struct{}
func (p *HelloService) Hello(request *hello_pb.String, reply *hello_pb.String) error {
reply.Value = "hello:" + request.GetValue()
return nil
}
func (p *HelloService) Echo(request *hello_pb.Message, reply *hello_pb.Message) error {
*reply = *request
return nil
}
func (p *HelloService) Static(request *hello_pb.String, reply *hello_pb.StaticFile) error {
data, err := ioutil.ReadFile("./testdata/" + request.Value)
if err != nil {
return err
}
reply.ContentType = mime.TypeByExtension(request.Value)
reply.ContentBody = data
return nil
}
func startRpcServer() {
hello_pb.RegisterHelloService(rpc.DefaultServer, new(HelloService))
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal("ListenTCP error:", err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal("Accept error:", err)
}
go rpc.ServeConn(conn)
}
}
func tryRpcClient() {
client, err := hello_pb.DialHelloService("tcp", "localhost:1234")
if err != nil {
log.Fatal(err)
}
reply, err := client.Hello(&hello_pb.String{Value: "gopher"})
if err != nil {
log.Fatal(err)
}
fmt.Println(reply.GetValue())
}
func main() {
go startRpcServer()
tryRpcClient()
}