forked from twitchtv/twirp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gocompat.go
93 lines (85 loc) · 2.32 KB
/
gocompat.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2018 Twitch Interactive, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the License is
// located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package main
import (
"context"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/golang/protobuf/proto"
"github.com/twitchtv/twirp"
"github.com/twitchtv/twirp/clientcompat/internal/clientcompat"
)
func main() {
var in clientcompat.ClientCompatMessage
inBytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("read stdin err: %v", err)
}
err = proto.Unmarshal(inBytes, &in)
if err != nil {
log.Fatalf("unmarshal err: %v", err)
}
client := clientcompat.NewCompatServiceProtobufClient(in.ServiceAddress, http.DefaultClient)
switch in.Method {
case clientcompat.ClientCompatMessage_NOOP:
if err := doNoop(client, in.Request); err != nil {
log.Fatalf("doNoop err: %v", err)
}
case clientcompat.ClientCompatMessage_METHOD:
if err := doMethod(client, in.Request); err != nil {
log.Fatalf("doMethod err: %v", err)
}
default:
log.Fatalf("unexpected method: %v", in.Method)
}
}
func doNoop(client clientcompat.CompatService, req []byte) error {
var e clientcompat.Empty
err := proto.Unmarshal(req, &e)
if err != nil {
return err
}
resp, err := client.NoopMethod(context.Background(), &e)
if err != nil {
errCode := err.(twirp.Error).Code()
os.Stderr.Write([]byte(errCode))
} else {
respBytes, err := proto.Marshal(resp)
if err != nil {
return err
}
os.Stdout.Write(respBytes)
}
return nil
}
func doMethod(client clientcompat.CompatService, req []byte) error {
var r clientcompat.Req
err := proto.Unmarshal(req, &r)
if err != nil {
return err
}
resp, err := client.Method(context.Background(), &r)
if err != nil {
errCode := err.(twirp.Error).Code()
os.Stderr.Write([]byte(errCode))
} else {
respBytes, err := proto.Marshal(resp)
if err != nil {
return err
}
os.Stdout.Write(respBytes)
}
return nil
}