Package list golang-github-go-kit-kit / 27b1f14
examples/addsvc2: copy over, incl. gRPC and Thrift Peter Bourgon 4 years ago
19 changed file(s) with 2526 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 package main
1
2 import (
3 "context"
4 "flag"
5 "fmt"
6 "net"
7 "net/http"
8 "os"
9 "os/signal"
10 "syscall"
11
12 "github.com/apache/thrift/lib/go/thrift"
13 "github.com/oklog/oklog/pkg/group"
14 stdopentracing "github.com/opentracing/opentracing-go"
15 zipkin "github.com/openzipkin/zipkin-go-opentracing"
16 stdprometheus "github.com/prometheus/client_golang/prometheus"
17 "google.golang.org/grpc"
18
19 "github.com/go-kit/kit/log"
20 "github.com/go-kit/kit/metrics"
21 "github.com/go-kit/kit/metrics/prometheus"
22
23 addpb "github.com/go-kit/kit/examples/addsvc2/pb"
24 addendpoint "github.com/go-kit/kit/examples/addsvc2/pkg/endpoint"
25 addservice "github.com/go-kit/kit/examples/addsvc2/pkg/service"
26 addtransport "github.com/go-kit/kit/examples/addsvc2/pkg/transport"
27 addthrift "github.com/go-kit/kit/examples/addsvc2/thrift/gen-go/addsvc"
28 )
29
30 func main() {
31 var (
32 debugAddr = flag.String("debug.addr", ":8080", "Debug and metrics listen address")
33 httpAddr = flag.String("http-addr", ":8081", "HTTP listen address")
34 grpcAddr = flag.String("grpc-addr", ":8082", "gRPC listen address")
35 thriftAddr = flag.String("thrift-addr", ":8082", "Thrift listen address")
36 thriftProtocol = flag.String("thrift.protocol", "binary", "binary, compact, json, simplejson")
37 thriftBufferSize = flag.Int("thrift.buffer.size", 0, "0 for unbuffered")
38 thriftFramed = flag.Bool("thrift.framed", false, "true to enable framing")
39 zipkinURL = flag.String("zipkin-url", "", "Zipkin collector URL e.g. http://localhost:9411/api/v1/spans")
40 )
41 flag.Parse()
42
43 var logger log.Logger
44 {
45 logger = log.NewLogfmtLogger(os.Stderr)
46 logger = log.With(logger, "ts", log.DefaultTimestampUTC)
47 logger = log.With(logger, "caller", log.DefaultCaller)
48 }
49
50 var tracer stdopentracing.Tracer
51 {
52 if *zipkinURL != "" {
53 logger.Log("zipkin", *zipkinURL)
54 collector, err := zipkin.NewHTTPCollector(*zipkinURL)
55 if err != nil {
56 logger.Log("err", err)
57 os.Exit(1)
58 }
59 defer collector.Close()
60 var (
61 debug = false
62 hostPort = "localhost:80"
63 serviceName = "addsvc"
64 )
65 tracer, err = zipkin.NewTracer(zipkin.NewRecorder(
66 collector, debug, hostPort, serviceName,
67 ))
68 if err != nil {
69 logger.Log("err", err)
70 os.Exit(1)
71 }
72 } else {
73 tracer = stdopentracing.GlobalTracer() // no-op
74 }
75 }
76
77 // Our metrics are dependencies, here we create them.
78 var ints, chars metrics.Counter
79 {
80 // Business-level metrics.
81 ints = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
82 Namespace: "example",
83 Subsystem: "addsvc",
84 Name: "integers_summed",
85 Help: "Total count of integers summed via the Sum method.",
86 }, []string{})
87 chars = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
88 Namespace: "example",
89 Subsystem: "addsvc",
90 Name: "characters_concatenated",
91 Help: "Total count of characters concatenated via the Concat method.",
92 }, []string{})
93 }
94 var duration metrics.Histogram
95 {
96 // Endpoint-level metrics.
97 duration = prometheus.NewSummaryFrom(stdprometheus.SummaryOpts{
98 Namespace: "example",
99 Subsystem: "addsvc",
100 Name: "request_duration_seconds",
101 Help: "Request duration in seconds.",
102 }, []string{"method", "success"})
103 }
104
105 var (
106 service = addservice.New(logger, ints, chars)
107 endpoints = addendpoint.New(service, logger, duration, tracer)
108 httpHandler = addtransport.NewHTTPHandler(context.Background(), endpoints, logger, tracer)
109 grpcServer = addtransport.MakeGRPCServer(endpoints, tracer, logger)
110 thriftHandler = addtransport.MakeThriftHandler(context.Background(), endpoints)
111 )
112
113 var g group.Group
114 {
115 debugListener, err := net.Listen("tcp", *debugAddr)
116 if err != nil {
117 logger.Log("transport", "debug/HTTP", "during", "Listen", "err", err)
118 os.Exit(1)
119 }
120 g.Add(func() error {
121 logger.Log("transport", "debug/HTTP", "addr", *debugAddr)
122 return http.Serve(debugListener, http.DefaultServeMux)
123 }, func(error) {
124 debugListener.Close()
125 })
126 }
127 {
128 httpListener, err := net.Listen("tcp", *httpAddr)
129 if err != nil {
130 logger.Log("transport", "HTTP", "during", "Listen", "err", err)
131 os.Exit(1)
132 }
133 g.Add(func() error {
134 logger.Log("transport", "HTTP", "addr", *httpAddr)
135 return http.Serve(httpListener, httpHandler)
136 }, func(error) {
137 httpListener.Close()
138 })
139 }
140 {
141 grpcListener, err := net.Listen("tcp", *grpcAddr)
142 if err != nil {
143 logger.Log("transport", "gRPC", "during", "Listen", "err", err)
144 os.Exit(1)
145 }
146 g.Add(func() error {
147 logger.Log("transport", "gRPC", "addr", *grpcAddr)
148 baseServer := grpc.NewServer()
149 addpb.RegisterAddServer(baseServer, grpcServer)
150 return baseServer.Serve(grpcListener)
151 }, func(error) {
152 grpcListener.Close()
153 })
154 }
155 {
156 thriftSocket, err := thrift.NewTServerSocket(*thriftAddr)
157 if err != nil {
158 logger.Log("transport", "Thrift", "during", "Listen", "err", err)
159 os.Exit(1)
160 }
161 g.Add(func() error {
162 logger.Log("transport", "Thrift", "addr", *thriftAddr)
163 var protocolFactory thrift.TProtocolFactory
164 switch *thriftProtocol {
165 case "binary":
166 protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
167 case "compact":
168 protocolFactory = thrift.NewTCompactProtocolFactory()
169 case "json":
170 protocolFactory = thrift.NewTJSONProtocolFactory()
171 case "simplejson":
172 protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
173 default:
174 return fmt.Errorf("invalid Thrift protocol %q", *thriftProtocol)
175 }
176 var transportFactory thrift.TTransportFactory
177 if *thriftBufferSize > 0 {
178 transportFactory = thrift.NewTBufferedTransportFactory(*thriftBufferSize)
179 } else {
180 transportFactory = thrift.NewTTransportFactory()
181 }
182 if *thriftFramed {
183 transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
184 }
185 return thrift.NewTSimpleServer4(
186 addthrift.NewAddServiceProcessor(thriftHandler),
187 thriftSocket,
188 transportFactory,
189 protocolFactory,
190 ).Serve()
191 }, func(error) {
192 thriftSocket.Close()
193 })
194 }
195 {
196 cancelInterrupt := make(chan struct{})
197 g.Add(func() error {
198 c := make(chan os.Signal, 1)
199 signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
200 select {
201 case sig := <-c:
202 return fmt.Errorf("received signal %s", sig)
203 case <-cancelInterrupt:
204 return nil
205 }
206 }, func(error) {
207 close(cancelInterrupt)
208 })
209 }
210 logger.Log("exit", g.Run())
211 }
0 package main
1
2 import (
3 "fmt"
4 "net/http"
5 "os"
6 "strings"
7 "testing"
8
9 "github.com/pact-foundation/pact-go/dsl"
10 )
11
12 func TestPactStringsvcUppercase(t *testing.T) {
13 if os.Getenv("WRITE_PACTS") == "" {
14 t.Skip("skipping Pact contracts; set WRITE_PACTS environment variable to enable")
15 }
16
17 pact := dsl.Pact{
18 Port: 6666,
19 Consumer: "addsvc",
20 Provider: "stringsvc",
21 }
22 defer pact.Teardown()
23
24 pact.AddInteraction().
25 UponReceiving("stringsvc uppercase").
26 WithRequest(dsl.Request{
27 Headers: map[string]string{"Content-Type": "application/json; charset=utf-8"},
28 Method: "POST",
29 Path: "/uppercase",
30 Body: `{"s":"foo"}`,
31 }).
32 WillRespondWith(dsl.Response{
33 Status: 200,
34 Headers: map[string]string{"Content-Type": "application/json; charset=utf-8"},
35 Body: `{"v":"FOO"}`,
36 })
37
38 if err := pact.Verify(func() error {
39 u := fmt.Sprintf("http://localhost:%d/uppercase", pact.Server.Port)
40 req, err := http.NewRequest("POST", u, strings.NewReader(`{"s":"foo"}`))
41 if err != nil {
42 return err
43 }
44 req.Header.Set("Content-Type", "application/json; charset=utf-8")
45 if _, err = http.DefaultClient.Do(req); err != nil {
46 return err
47 }
48 return nil
49 }); err != nil {
50 t.Fatal(err)
51 }
52
53 pact.WritePact()
54 }
0 package main
1
2 import (
3 "context"
4 "io/ioutil"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9
10 "github.com/go-kit/kit/log"
11 "github.com/go-kit/kit/metrics/discard"
12 "github.com/opentracing/opentracing-go"
13
14 addendpoint "github.com/go-kit/kit/examples/addsvc2/pkg/endpoint"
15 addservice "github.com/go-kit/kit/examples/addsvc2/pkg/service"
16 addtransport "github.com/go-kit/kit/examples/addsvc2/pkg/transport"
17 )
18
19 func TestHTTP(t *testing.T) {
20 svc := addservice.New(log.NewNopLogger(), discard.NewCounter(), discard.NewCounter())
21 eps := addendpoint.New(svc, log.NewNopLogger(), discard.NewHistogram(), opentracing.GlobalTracer())
22 mux := addtransport.NewHTTPHandler(context.Background(), eps, log.NewNopLogger(), opentracing.GlobalTracer())
23 srv := httptest.NewServer(mux)
24 defer srv.Close()
25
26 for _, testcase := range []struct {
27 method, url, body, want string
28 }{
29 {"GET", srv.URL + "/concat", `{"a":"1","b":"2"}`, `{"v":"12"}`},
30 {"GET", srv.URL + "/sum", `{"a":1,"b":2}`, `{"v":3}`},
31 } {
32 req, _ := http.NewRequest(testcase.method, testcase.url, strings.NewReader(testcase.body))
33 resp, _ := http.DefaultClient.Do(req)
34 body, _ := ioutil.ReadAll(resp.Body)
35 if want, have := testcase.want, strings.TrimSpace(string(body)); want != have {
36 t.Errorf("%s %s %s: want %q, have %q", testcase.method, testcase.url, testcase.body, want, have)
37 }
38 }
39 }
0 // Code generated by protoc-gen-go. DO NOT EDIT.
1 // source: addsvc.proto
2
3 /*
4 Package pb is a generated protocol buffer package.
5
6 It is generated from these files:
7 addsvc.proto
8
9 It has these top-level messages:
10 SumRequest
11 SumReply
12 ConcatRequest
13 ConcatReply
14 */
15 package pb
16
17 import proto "github.com/golang/protobuf/proto"
18 import fmt "fmt"
19 import math "math"
20
21 import (
22 context "golang.org/x/net/context"
23 grpc "google.golang.org/grpc"
24 )
25
26 // Reference imports to suppress errors if they are not otherwise used.
27 var _ = proto.Marshal
28 var _ = fmt.Errorf
29 var _ = math.Inf
30
31 // This is a compile-time assertion to ensure that this generated file
32 // is compatible with the proto package it is being compiled against.
33 // A compilation error at this line likely means your copy of the
34 // proto package needs to be updated.
35 const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
36
37 // The sum request contains two parameters.
38 type SumRequest struct {
39 A int64 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"`
40 B int64 `protobuf:"varint,2,opt,name=b" json:"b,omitempty"`
41 }
42
43 func (m *SumRequest) Reset() { *m = SumRequest{} }
44 func (m *SumRequest) String() string { return proto.CompactTextString(m) }
45 func (*SumRequest) ProtoMessage() {}
46 func (*SumRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
47
48 func (m *SumRequest) GetA() int64 {
49 if m != nil {
50 return m.A
51 }
52 return 0
53 }
54
55 func (m *SumRequest) GetB() int64 {
56 if m != nil {
57 return m.B
58 }
59 return 0
60 }
61
62 // The sum response contains the result of the calculation.
63 type SumReply struct {
64 V int64 `protobuf:"varint,1,opt,name=v" json:"v,omitempty"`
65 Err string `protobuf:"bytes,2,opt,name=err" json:"err,omitempty"`
66 }
67
68 func (m *SumReply) Reset() { *m = SumReply{} }
69 func (m *SumReply) String() string { return proto.CompactTextString(m) }
70 func (*SumReply) ProtoMessage() {}
71 func (*SumReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
72
73 func (m *SumReply) GetV() int64 {
74 if m != nil {
75 return m.V
76 }
77 return 0
78 }
79
80 func (m *SumReply) GetErr() string {
81 if m != nil {
82 return m.Err
83 }
84 return ""
85 }
86
87 // The Concat request contains two parameters.
88 type ConcatRequest struct {
89 A string `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
90 B string `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"`
91 }
92
93 func (m *ConcatRequest) Reset() { *m = ConcatRequest{} }
94 func (m *ConcatRequest) String() string { return proto.CompactTextString(m) }
95 func (*ConcatRequest) ProtoMessage() {}
96 func (*ConcatRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
97
98 func (m *ConcatRequest) GetA() string {
99 if m != nil {
100 return m.A
101 }
102 return ""
103 }
104
105 func (m *ConcatRequest) GetB() string {
106 if m != nil {
107 return m.B
108 }
109 return ""
110 }
111
112 // The Concat response contains the result of the concatenation.
113 type ConcatReply struct {
114 V string `protobuf:"bytes,1,opt,name=v" json:"v,omitempty"`
115 Err string `protobuf:"bytes,2,opt,name=err" json:"err,omitempty"`
116 }
117
118 func (m *ConcatReply) Reset() { *m = ConcatReply{} }
119 func (m *ConcatReply) String() string { return proto.CompactTextString(m) }
120 func (*ConcatReply) ProtoMessage() {}
121 func (*ConcatReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
122
123 func (m *ConcatReply) GetV() string {
124 if m != nil {
125 return m.V
126 }
127 return ""
128 }
129
130 func (m *ConcatReply) GetErr() string {
131 if m != nil {
132 return m.Err
133 }
134 return ""
135 }
136
137 func init() {
138 proto.RegisterType((*SumRequest)(nil), "pb.SumRequest")
139 proto.RegisterType((*SumReply)(nil), "pb.SumReply")
140 proto.RegisterType((*ConcatRequest)(nil), "pb.ConcatRequest")
141 proto.RegisterType((*ConcatReply)(nil), "pb.ConcatReply")
142 }
143
144 // Reference imports to suppress errors if they are not otherwise used.
145 var _ context.Context
146 var _ grpc.ClientConn
147
148 // This is a compile-time assertion to ensure that this generated file
149 // is compatible with the grpc package it is being compiled against.
150 const _ = grpc.SupportPackageIsVersion4
151
152 // Client API for Add service
153
154 type AddClient interface {
155 // Sums two integers.
156 Sum(ctx context.Context, in *SumRequest, opts ...grpc.CallOption) (*SumReply, error)
157 // Concatenates two strings
158 Concat(ctx context.Context, in *ConcatRequest, opts ...grpc.CallOption) (*ConcatReply, error)
159 }
160
161 type addClient struct {
162 cc *grpc.ClientConn
163 }
164
165 func NewAddClient(cc *grpc.ClientConn) AddClient {
166 return &addClient{cc}
167 }
168
169 func (c *addClient) Sum(ctx context.Context, in *SumRequest, opts ...grpc.CallOption) (*SumReply, error) {
170 out := new(SumReply)
171 err := grpc.Invoke(ctx, "/pb.Add/Sum", in, out, c.cc, opts...)
172 if err != nil {
173 return nil, err
174 }
175 return out, nil
176 }
177
178 func (c *addClient) Concat(ctx context.Context, in *ConcatRequest, opts ...grpc.CallOption) (*ConcatReply, error) {
179 out := new(ConcatReply)
180 err := grpc.Invoke(ctx, "/pb.Add/Concat", in, out, c.cc, opts...)
181 if err != nil {
182 return nil, err
183 }
184 return out, nil
185 }
186
187 // Server API for Add service
188
189 type AddServer interface {
190 // Sums two integers.
191 Sum(context.Context, *SumRequest) (*SumReply, error)
192 // Concatenates two strings
193 Concat(context.Context, *ConcatRequest) (*ConcatReply, error)
194 }
195
196 func RegisterAddServer(s *grpc.Server, srv AddServer) {
197 s.RegisterService(&_Add_serviceDesc, srv)
198 }
199
200 func _Add_Sum_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
201 in := new(SumRequest)
202 if err := dec(in); err != nil {
203 return nil, err
204 }
205 if interceptor == nil {
206 return srv.(AddServer).Sum(ctx, in)
207 }
208 info := &grpc.UnaryServerInfo{
209 Server: srv,
210 FullMethod: "/pb.Add/Sum",
211 }
212 handler := func(ctx context.Context, req interface{}) (interface{}, error) {
213 return srv.(AddServer).Sum(ctx, req.(*SumRequest))
214 }
215 return interceptor(ctx, in, info, handler)
216 }
217
218 func _Add_Concat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
219 in := new(ConcatRequest)
220 if err := dec(in); err != nil {
221 return nil, err
222 }
223 if interceptor == nil {
224 return srv.(AddServer).Concat(ctx, in)
225 }
226 info := &grpc.UnaryServerInfo{
227 Server: srv,
228 FullMethod: "/pb.Add/Concat",
229 }
230 handler := func(ctx context.Context, req interface{}) (interface{}, error) {
231 return srv.(AddServer).Concat(ctx, req.(*ConcatRequest))
232 }
233 return interceptor(ctx, in, info, handler)
234 }
235
236 var _Add_serviceDesc = grpc.ServiceDesc{
237 ServiceName: "pb.Add",
238 HandlerType: (*AddServer)(nil),
239 Methods: []grpc.MethodDesc{
240 {
241 MethodName: "Sum",
242 Handler: _Add_Sum_Handler,
243 },
244 {
245 MethodName: "Concat",
246 Handler: _Add_Concat_Handler,
247 },
248 },
249 Streams: []grpc.StreamDesc{},
250 Metadata: "addsvc.proto",
251 }
252
253 func init() { proto.RegisterFile("addsvc.proto", fileDescriptor0) }
254
255 var fileDescriptor0 = []byte{
256 // 189 bytes of a gzipped FileDescriptorProto
257 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0x4c, 0x49, 0x29,
258 0x2e, 0x4b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2a, 0x48, 0x52, 0xd2, 0xe0, 0xe2,
259 0x0a, 0x2e, 0xcd, 0x0d, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x11, 0xe2, 0xe1, 0x62, 0x4c, 0x94,
260 0x60, 0x54, 0x60, 0xd4, 0x60, 0x0e, 0x62, 0x4c, 0x04, 0xf1, 0x92, 0x24, 0x98, 0x20, 0xbc, 0x24,
261 0x25, 0x2d, 0x2e, 0x0e, 0xb0, 0xca, 0x82, 0x9c, 0x4a, 0x90, 0x4c, 0x19, 0x4c, 0x5d, 0x99, 0x90,
262 0x00, 0x17, 0x73, 0x6a, 0x51, 0x11, 0x58, 0x25, 0x67, 0x10, 0x88, 0xa9, 0xa4, 0xcd, 0xc5, 0xeb,
263 0x9c, 0x9f, 0x97, 0x9c, 0x58, 0x82, 0x61, 0x30, 0x27, 0x8a, 0xc1, 0x9c, 0x20, 0x83, 0x75, 0xb9,
264 0xb8, 0x61, 0x8a, 0x51, 0xcc, 0xe6, 0xc4, 0x6a, 0xb6, 0x51, 0x0c, 0x17, 0xb3, 0x63, 0x4a, 0x8a,
265 0x90, 0x2a, 0x17, 0x73, 0x70, 0x69, 0xae, 0x10, 0x9f, 0x5e, 0x41, 0x92, 0x1e, 0xc2, 0x07, 0x52,
266 0x3c, 0x70, 0x7e, 0x41, 0x4e, 0xa5, 0x12, 0x83, 0x90, 0x1e, 0x17, 0x1b, 0xc4, 0x70, 0x21, 0x41,
267 0x90, 0x0c, 0x8a, 0xab, 0xa4, 0xf8, 0x91, 0x85, 0xc0, 0xea, 0x93, 0xd8, 0xc0, 0x41, 0x63, 0x0c,
268 0x08, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x37, 0x81, 0x99, 0x2a, 0x01, 0x00, 0x00,
269 }
0 syntax = "proto3";
1
2 package pb;
3
4 // The Add service definition.
5 service Add {
6 // Sums two integers.
7 rpc Sum (SumRequest) returns (SumReply) {}
8
9 // Concatenates two strings
10 rpc Concat (ConcatRequest) returns (ConcatReply) {}
11 }
12
13 // The sum request contains two parameters.
14 message SumRequest {
15 int64 a = 1;
16 int64 b = 2;
17 }
18
19 // The sum response contains the result of the calculation.
20 message SumReply {
21 int64 v = 1;
22 string err = 2;
23 }
24
25 // The Concat request contains two parameters.
26 message ConcatRequest {
27 string a = 1;
28 string b = 2;
29 }
30
31 // The Concat response contains the result of the concatenation.
32 message ConcatReply {
33 string v = 1;
34 string err = 2;
35 }
0 #!/usr/bin/env sh
1
2 # Install proto3 from source
3 # brew install autoconf automake libtool
4 # git clone https://github.com/google/protobuf
5 # ./autogen.sh ; ./configure ; make ; make install
6 #
7 # Update protoc Go bindings via
8 # go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
9 #
10 # See also
11 # https://github.com/grpc/grpc-go/tree/master/examples
12
13 protoc addsvc.proto --go_out=plugins=grpc:.
0 package endpoint
1
2 import (
3 "context"
4 "fmt"
5 "time"
6
7 "github.com/go-kit/kit/endpoint"
8 "github.com/go-kit/kit/log"
9 "github.com/go-kit/kit/metrics"
10 )
11
12 // InstrumentingMiddleware returns an endpoint middleware that records
13 // the duration of each invocation to the passed histogram. The middleware adds
14 // a single field: "success", which is "true" if no error is returned, and
15 // "false" otherwise.
16 func InstrumentingMiddleware(duration metrics.Histogram) endpoint.Middleware {
17 return func(next endpoint.Endpoint) endpoint.Endpoint {
18 return func(ctx context.Context, request interface{}) (response interface{}, err error) {
19
20 defer func(begin time.Time) {
21 duration.With("success", fmt.Sprint(err == nil)).Observe(time.Since(begin).Seconds())
22 }(time.Now())
23 return next(ctx, request)
24
25 }
26 }
27 }
28
29 // LoggingMiddleware returns an endpoint middleware that logs the
30 // duration of each invocation, and the resulting error, if any.
31 func LoggingMiddleware(logger log.Logger) endpoint.Middleware {
32 return func(next endpoint.Endpoint) endpoint.Endpoint {
33 return func(ctx context.Context, request interface{}) (response interface{}, err error) {
34
35 defer func(begin time.Time) {
36 logger.Log("transport_error", err, "took", time.Since(begin))
37 }(time.Now())
38 return next(ctx, request)
39
40 }
41 }
42 }
0 package endpoint
1
2 import (
3 "context"
4
5 rl "github.com/juju/ratelimit"
6 stdopentracing "github.com/opentracing/opentracing-go"
7 "github.com/sony/gobreaker"
8
9 "github.com/go-kit/kit/circuitbreaker"
10 "github.com/go-kit/kit/endpoint"
11 "github.com/go-kit/kit/log"
12 "github.com/go-kit/kit/metrics"
13 "github.com/go-kit/kit/ratelimit"
14 "github.com/go-kit/kit/tracing/opentracing"
15
16 "github.com/go-kit/kit/examples/addsvc2/pkg/service"
17 )
18
19 // Set collects all of the endpoints that compose an add service. It's meant to
20 // be used as a helper struct, to collect all of the endpoints into a single
21 // parameter.
22 type Set struct {
23 SumEndpoint endpoint.Endpoint
24 ConcatEndpoint endpoint.Endpoint
25 }
26
27 // New returns a Set that wraps the provided server, and wires in all of the
28 // expected endpoint middlewares via the various parameters.
29 func New(svc service.Service, logger log.Logger, duration metrics.Histogram, trace stdopentracing.Tracer) Set {
30 var sumEndpoint endpoint.Endpoint
31 {
32 sumEndpoint = MakeSumEndpoint(svc)
33 sumEndpoint = ratelimit.NewTokenBucketLimiter(rl.NewBucketWithRate(1, 1))(sumEndpoint)
34 sumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{}))(sumEndpoint)
35 sumEndpoint = opentracing.TraceServer(trace, "Sum")(sumEndpoint)
36 sumEndpoint = LoggingMiddleware(log.With(logger, "method", "Sum"))(sumEndpoint)
37 sumEndpoint = InstrumentingMiddleware(duration.With("method", "Sum"))(sumEndpoint)
38 }
39 var concatEndpoint endpoint.Endpoint
40 {
41 concatEndpoint = MakeConcatEndpoint(svc)
42 concatEndpoint = ratelimit.NewTokenBucketLimiter(rl.NewBucketWithRate(100, 100))(concatEndpoint)
43 concatEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{}))(concatEndpoint)
44 concatEndpoint = opentracing.TraceServer(trace, "Concat")(concatEndpoint)
45 concatEndpoint = LoggingMiddleware(log.With(logger, "method", "Concat"))(concatEndpoint)
46 concatEndpoint = InstrumentingMiddleware(duration.With("method", "Concat"))(concatEndpoint)
47 }
48 return Set{
49 SumEndpoint: sumEndpoint,
50 ConcatEndpoint: concatEndpoint,
51 }
52 }
53
54 // MakeSumEndpoint constructs a Sum endpoint wrapping the service.
55 func MakeSumEndpoint(s service.Service) endpoint.Endpoint {
56 return func(ctx context.Context, request interface{}) (response interface{}, err error) {
57 req := request.(SumRequest)
58 v, err := s.Sum(ctx, req.A, req.B)
59 return SumResponse{V: v, Err: err}, nil
60 }
61 }
62
63 // MakeConcatEndpoint constructs a Concat endpoint wrapping the service.
64 func MakeConcatEndpoint(s service.Service) endpoint.Endpoint {
65 return func(ctx context.Context, request interface{}) (response interface{}, err error) {
66 req := request.(ConcatRequest)
67 v, err := s.Concat(ctx, req.A, req.B)
68 return ConcatResponse{V: v, Err: err}, nil
69 }
70 }
71
72 // Failer is an interface that should be implemented by response types.
73 // Response encoders can check if responses are Failer, and if so if they've
74 // failed, and if so encode them using a separate write path based on the error.
75 type Failer interface {
76 Failed() error
77 }
78
79 // SumRequest collects the request parameters for the Sum method.
80 type SumRequest struct {
81 A, B int
82 }
83
84 // SumResponse collects the response values for the Sum method.
85 type SumResponse struct {
86 V int `json:"v"`
87 Err error `json:"-"` // should be intercepted by Failed/errorEncoder
88 }
89
90 // Failed implements Failer.
91 func (r SumResponse) Failed() error { return r.Err }
92
93 // ConcatRequest collects the request parameters for the Concat method.
94 type ConcatRequest struct {
95 A, B string
96 }
97
98 // ConcatResponse collects the response values for the Concat method.
99 type ConcatResponse struct {
100 V string `json:"v"`
101 Err error `json:"-"`
102 }
103
104 // Failed implements Failer.
105 func (r ConcatResponse) Failed() error { return r.Err }
0 package service
1
2 import (
3 "context"
4
5 "github.com/go-kit/kit/log"
6 "github.com/go-kit/kit/metrics"
7 )
8
9 // Middleware describes a service (as opposed to endpoint) middleware.
10 type Middleware func(Service) Service
11
12 // LoggingMiddleware takes a logger as a dependency
13 // and returns a ServiceMiddleware.
14 func LoggingMiddleware(logger log.Logger) Middleware {
15 return func(next Service) Service {
16 return loggingMiddleware{logger, next}
17 }
18 }
19
20 type loggingMiddleware struct {
21 logger log.Logger
22 next Service
23 }
24
25 func (mw loggingMiddleware) Sum(ctx context.Context, a, b int) (v int, err error) {
26 defer func() {
27 mw.logger.Log("method", "Sum", "a", a, "b", b, "v", v, "err", err)
28 }()
29 return mw.next.Sum(ctx, a, b)
30 }
31
32 func (mw loggingMiddleware) Concat(ctx context.Context, a, b string) (v string, err error) {
33 defer func() {
34 mw.logger.Log("method", "Concat", "a", a, "b", b, "v", v, "err", err)
35 }()
36 return mw.next.Concat(ctx, a, b)
37 }
38
39 // InstrumentingMiddleware returns a service middleware that instruments
40 // the number of integers summed and characters concatenated over the lifetime of
41 // the service.
42 func InstrumentingMiddleware(ints, chars metrics.Counter) Middleware {
43 return func(next Service) Service {
44 return instrumentingMiddleware{
45 ints: ints,
46 chars: chars,
47 next: next,
48 }
49 }
50 }
51
52 type instrumentingMiddleware struct {
53 ints metrics.Counter
54 chars metrics.Counter
55 next Service
56 }
57
58 func (mw instrumentingMiddleware) Sum(ctx context.Context, a, b int) (int, error) {
59 v, err := mw.next.Sum(ctx, a, b)
60 mw.ints.Add(float64(v))
61 return v, err
62 }
63
64 func (mw instrumentingMiddleware) Concat(ctx context.Context, a, b string) (string, error) {
65 v, err := mw.next.Concat(ctx, a, b)
66 mw.chars.Add(float64(len(v)))
67 return v, err
68 }
0 package service
1
2 import (
3 "context"
4 "errors"
5
6 "github.com/go-kit/kit/log"
7 "github.com/go-kit/kit/metrics"
8 )
9
10 // Service describes a service that adds things together.
11 type Service interface {
12 Sum(ctx context.Context, a, b int) (int, error)
13 Concat(ctx context.Context, a, b string) (string, error)
14 }
15
16 // New returns a basic Service with all of the expected middlewares wired in.
17 func New(logger log.Logger, ints, chars metrics.Counter) Service {
18 var svc Service
19 {
20 svc = NewBasicService()
21 svc = LoggingMiddleware(logger)(svc)
22 svc = InstrumentingMiddleware(ints, chars)(svc)
23 }
24 return svc
25 }
26
27 var (
28 // ErrTwoZeroes is an arbitrary business rule for the Add method.
29 ErrTwoZeroes = errors.New("can't sum two zeroes")
30
31 // ErrIntOverflow protects the Add method. We've decided that this error
32 // indicates a misbehaving service and should count against e.g. circuit
33 // breakers. So, we return it directly in endpoints, to illustrate the
34 // difference. In a real service, this probably wouldn't be the case.
35 ErrIntOverflow = errors.New("integer overflow")
36
37 // ErrMaxSizeExceeded protects the Concat method.
38 ErrMaxSizeExceeded = errors.New("result exceeds maximum size")
39 )
40
41 // NewBasicService returns a naïve, stateless implementation of Service.
42 func NewBasicService() Service {
43 return basicService{}
44 }
45
46 type basicService struct{}
47
48 const (
49 intMax = 1<<31 - 1
50 intMin = -(intMax + 1)
51 maxLen = 10
52 )
53
54 func (s basicService) Sum(_ context.Context, a, b int) (int, error) {
55 if a == 0 && b == 0 {
56 return 0, ErrTwoZeroes
57 }
58 if (b > 0 && a > (intMax-b)) || (b < 0 && a < (intMin-b)) {
59 return 0, ErrIntOverflow
60 }
61 return a + b, nil
62 }
63
64 // Concat implements Service.
65 func (s basicService) Concat(_ context.Context, a, b string) (string, error) {
66 if len(a)+len(b) > maxLen {
67 return "", ErrMaxSizeExceeded
68 }
69 return a + b, nil
70 }
0 package transport
1
2 import (
3 "context"
4 "errors"
5
6 stdopentracing "github.com/opentracing/opentracing-go"
7 oldcontext "golang.org/x/net/context"
8
9 "github.com/go-kit/kit/log"
10 "github.com/go-kit/kit/tracing/opentracing"
11 grpctransport "github.com/go-kit/kit/transport/grpc"
12
13 "github.com/go-kit/kit/examples/addsvc2/pb"
14 "github.com/go-kit/kit/examples/addsvc2/pkg/endpoint"
15 )
16
17 // MakeGRPCServer makes a set of endpoints available as a gRPC AddServer.
18 func MakeGRPCServer(endpoints endpoint.Set, tracer stdopentracing.Tracer, logger log.Logger) pb.AddServer {
19 options := []grpctransport.ServerOption{
20 grpctransport.ServerErrorLogger(logger),
21 }
22 return &grpcServer{
23 sum: grpctransport.NewServer(
24 endpoints.SumEndpoint,
25 decodeGRPCSumRequest,
26 encodeGRPCSumResponse,
27 append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Sum", logger)))...,
28 ),
29 concat: grpctransport.NewServer(
30 endpoints.ConcatEndpoint,
31 decodeGRPCConcatRequest,
32 encodeGRPCConcatResponse,
33 append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Concat", logger)))...,
34 ),
35 }
36 }
37
38 type grpcServer struct {
39 sum grpctransport.Handler
40 concat grpctransport.Handler
41 }
42
43 func (s *grpcServer) Sum(ctx oldcontext.Context, req *pb.SumRequest) (*pb.SumReply, error) {
44 _, rep, err := s.sum.ServeGRPC(ctx, req)
45 if err != nil {
46 return nil, err
47 }
48 return rep.(*pb.SumReply), nil
49 }
50
51 func (s *grpcServer) Concat(ctx oldcontext.Context, req *pb.ConcatRequest) (*pb.ConcatReply, error) {
52 _, rep, err := s.concat.ServeGRPC(ctx, req)
53 if err != nil {
54 return nil, err
55 }
56 return rep.(*pb.ConcatReply), nil
57 }
58
59 // decodeGRPCSumRequest is a transport/grpc.DecodeRequestFunc that converts a
60 // gRPC sum request to a user-domain sum request. Primarily useful in a server.
61 func decodeGRPCSumRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
62 req := grpcReq.(*pb.SumRequest)
63 return endpoint.SumRequest{A: int(req.A), B: int(req.B)}, nil
64 }
65
66 // decodeGRPCConcatRequest is a transport/grpc.DecodeRequestFunc that converts a
67 // gRPC concat request to a user-domain concat request. Primarily useful in a
68 // server.
69 func decodeGRPCConcatRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {
70 req := grpcReq.(*pb.ConcatRequest)
71 return endpoint.ConcatRequest{A: req.A, B: req.B}, nil
72 }
73
74 // decodeGRPCSumResponse is a transport/grpc.DecodeResponseFunc that converts a
75 // gRPC sum reply to a user-domain sum response. Primarily useful in a client.
76 func decodeGRPCSumResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {
77 reply := grpcReply.(*pb.SumReply)
78 return endpoint.SumResponse{V: int(reply.V), Err: str2err(reply.Err)}, nil
79 }
80
81 // decodeGRPCConcatResponse is a transport/grpc.DecodeResponseFunc that converts
82 // a gRPC concat reply to a user-domain concat response. Primarily useful in a
83 // client.
84 func decodeGRPCConcatResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {
85 reply := grpcReply.(*pb.ConcatReply)
86 return endpoint.ConcatResponse{V: reply.V, Err: str2err(reply.Err)}, nil
87 }
88
89 // encodeGRPCSumResponse is a transport/grpc.EncodeResponseFunc that converts a
90 // user-domain sum response to a gRPC sum reply. Primarily useful in a server.
91 func encodeGRPCSumResponse(_ context.Context, response interface{}) (interface{}, error) {
92 resp := response.(endpoint.SumResponse)
93 return &pb.SumReply{V: int64(resp.V), Err: err2str(resp.Err)}, nil
94 }
95
96 // encodeGRPCConcatResponse is a transport/grpc.EncodeResponseFunc that converts
97 // a user-domain concat response to a gRPC concat reply. Primarily useful in a
98 // server.
99 func encodeGRPCConcatResponse(_ context.Context, response interface{}) (interface{}, error) {
100 resp := response.(endpoint.ConcatResponse)
101 return &pb.ConcatReply{V: resp.V, Err: err2str(resp.Err)}, nil
102 }
103
104 // encodeGRPCSumRequest is a transport/grpc.EncodeRequestFunc that converts a
105 // user-domain sum request to a gRPC sum request. Primarily useful in a client.
106 func encodeGRPCSumRequest(_ context.Context, request interface{}) (interface{}, error) {
107 req := request.(endpoint.SumRequest)
108 return &pb.SumRequest{A: int64(req.A), B: int64(req.B)}, nil
109 }
110
111 // encodeGRPCConcatRequest is a transport/grpc.EncodeRequestFunc that converts a
112 // user-domain concat request to a gRPC concat request. Primarily useful in a
113 // client.
114 func encodeGRPCConcatRequest(_ context.Context, request interface{}) (interface{}, error) {
115 req := request.(endpoint.ConcatRequest)
116 return &pb.ConcatRequest{A: req.A, B: req.B}, nil
117 }
118
119 // These annoying helper functions are required to translate Go error types to
120 // and from strings, which is the type we use in our IDLs to represent errors.
121 // There is special casing to treat empty strings as nil errors.
122
123 func str2err(s string) error {
124 if s == "" {
125 return nil
126 }
127 return errors.New(s)
128 }
129
130 func err2str(err error) string {
131 if err == nil {
132 return ""
133 }
134 return err.Error()
135 }
0 package transport
1
2 import (
3 "bytes"
4 "context"
5 "encoding/json"
6 "errors"
7 "io/ioutil"
8 "net/http"
9
10 stdopentracing "github.com/opentracing/opentracing-go"
11 "github.com/prometheus/client_golang/prometheus/promhttp"
12
13 "github.com/go-kit/kit/log"
14 "github.com/go-kit/kit/tracing/opentracing"
15 httptransport "github.com/go-kit/kit/transport/http"
16
17 "github.com/go-kit/kit/examples/addsvc2/pkg/endpoint"
18 "github.com/go-kit/kit/examples/addsvc2/pkg/service"
19 )
20
21 // NewHTTPHandler returns an HTTP handler that makes a set of endpoints
22 // available on predefined paths.
23 func NewHTTPHandler(ctx context.Context, endpoints endpoint.Set, logger log.Logger, trace stdopentracing.Tracer) http.Handler {
24 options := []httptransport.ServerOption{
25 httptransport.ServerErrorEncoder(errorEncoder),
26 httptransport.ServerErrorLogger(logger),
27 }
28 m := http.NewServeMux()
29 m.Handle("/sum", httptransport.NewServer(
30 endpoints.SumEndpoint,
31 decodeHTTPSumRequest,
32 encodeHTTPGenericResponse,
33 append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(trace, "Sum", logger)))...,
34 ))
35 m.Handle("/concat", httptransport.NewServer(
36 endpoints.ConcatEndpoint,
37 decodeHTTPConcatRequest,
38 encodeHTTPGenericResponse,
39 append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(trace, "Concat", logger)))...,
40 ))
41 m.Handle("/metrics", promhttp.Handler())
42 return m
43 }
44
45 func errorEncoder(_ context.Context, err error, w http.ResponseWriter) {
46 w.WriteHeader(err2code(err))
47 json.NewEncoder(w).Encode(errorWrapper{Error: err.Error()})
48 }
49
50 func err2code(err error) int {
51 switch err {
52 case service.ErrTwoZeroes, service.ErrMaxSizeExceeded, service.ErrIntOverflow:
53 return http.StatusBadRequest
54 }
55 return http.StatusInternalServerError
56 }
57
58 func errorDecoder(r *http.Response) error {
59 var w errorWrapper
60 if err := json.NewDecoder(r.Body).Decode(&w); err != nil {
61 return err
62 }
63 return errors.New(w.Error)
64 }
65
66 type errorWrapper struct {
67 Error string `json:"error"`
68 }
69
70 // decodeHTTPSumRequest is a transport/http.DecodeRequestFunc that decodes a
71 // JSON-encoded sum request from the HTTP request body. Primarily useful in a
72 // server.
73 func decodeHTTPSumRequest(_ context.Context, r *http.Request) (interface{}, error) {
74 var req endpoint.SumRequest
75 err := json.NewDecoder(r.Body).Decode(&req)
76 return req, err
77 }
78
79 // decodeHTTPConcatRequest is a transport/http.DecodeRequestFunc that decodes a
80 // JSON-encoded concat request from the HTTP request body. Primarily useful in a
81 // server.
82 func decodeHTTPConcatRequest(_ context.Context, r *http.Request) (interface{}, error) {
83 var req endpoint.ConcatRequest
84 err := json.NewDecoder(r.Body).Decode(&req)
85 return req, err
86 }
87
88 // decodeHTTPSumResponse is a transport/http.DecodeResponseFunc that decodes a
89 // JSON-encoded sum response from the HTTP response body. If the response has a
90 // non-200 status code, we will interpret that as an error and attempt to decode
91 // the specific error message from the response body. Primarily useful in a
92 // client.
93 func decodeHTTPSumResponse(_ context.Context, r *http.Response) (interface{}, error) {
94 if r.StatusCode != http.StatusOK {
95 return nil, errors.New(r.Status)
96 }
97 var resp endpoint.SumResponse
98 err := json.NewDecoder(r.Body).Decode(&resp)
99 return resp, err
100 }
101
102 // decodeHTTPConcatResponse is a transport/http.DecodeResponseFunc that decodes
103 // a JSON-encoded concat response from the HTTP response body. If the response
104 // has a non-200 status code, we will interpret that as an error and attempt to
105 // decode the specific error message from the response body. Primarily useful in
106 // a client.
107 func decodeHTTPConcatResponse(_ context.Context, r *http.Response) (interface{}, error) {
108 if r.StatusCode != http.StatusOK {
109 return nil, errors.New(r.Status)
110 }
111 var resp endpoint.ConcatResponse
112 err := json.NewDecoder(r.Body).Decode(&resp)
113 return resp, err
114 }
115
116 // encodeHTTPGenericRequest is a transport/http.EncodeRequestFunc that
117 // JSON-encodes any request to the request body. Primarily useful in a client.
118 func encodeHTTPGenericRequest(_ context.Context, r *http.Request, request interface{}) error {
119 var buf bytes.Buffer
120 if err := json.NewEncoder(&buf).Encode(request); err != nil {
121 return err
122 }
123 r.Body = ioutil.NopCloser(&buf)
124 return nil
125 }
126
127 // encodeHTTPGenericResponse is a transport/http.EncodeResponseFunc that encodes
128 // the response as JSON to the response writer. Primarily useful in a server.
129 func encodeHTTPGenericResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
130 if f, ok := response.(endpoint.Failer); ok && f.Failed() != nil {
131 errorEncoder(ctx, f.Failed(), w)
132 return nil
133 }
134 w.Header().Set("Content-Type", "application/json; charset=utf-8")
135 return json.NewEncoder(w).Encode(response)
136 }
0 package transport
1
2 import (
3 "context"
4
5 "github.com/go-kit/kit/endpoint"
6 addendpoint "github.com/go-kit/kit/examples/addsvc2/pkg/endpoint"
7 "github.com/go-kit/kit/examples/addsvc2/pkg/service"
8 thriftadd "github.com/go-kit/kit/examples/addsvc2/thrift/gen-go/addsvc"
9 )
10
11 // MakeThriftHandler makes a set of endpoints available as a Thrift service.
12 func MakeThriftHandler(ctx context.Context, endpoints addendpoint.Set) thriftadd.AddService {
13 return &thriftServer{
14 ctx: ctx,
15 endpoints: endpoints,
16 }
17 }
18
19 type thriftServer struct {
20 ctx context.Context
21 endpoints addendpoint.Set
22 }
23
24 func (s *thriftServer) Sum(a int64, b int64) (*thriftadd.SumReply, error) {
25 request := addendpoint.SumRequest{A: int(a), B: int(b)}
26 response, err := s.endpoints.SumEndpoint(s.ctx, request)
27 if err != nil {
28 return nil, err
29 }
30 resp := response.(addendpoint.SumResponse)
31 return &thriftadd.SumReply{Value: int64(resp.V), Err: err2str(resp.Err)}, nil
32 }
33
34 func (s *thriftServer) Concat(a string, b string) (*thriftadd.ConcatReply, error) {
35 request := addendpoint.ConcatRequest{A: a, B: b}
36 response, err := s.endpoints.ConcatEndpoint(s.ctx, request)
37 if err != nil {
38 return nil, err
39 }
40 resp := response.(addendpoint.ConcatResponse)
41 return &thriftadd.ConcatReply{Value: resp.V, Err: err2str(resp.Err)}, nil
42 }
43
44 // MakeThriftSumEndpoint returns an endpoint that invokes the passed Thrift client.
45 // Useful only in clients, and only until a proper transport/thrift.Client exists.
46 func MakeThriftSumEndpoint(client *thriftadd.AddServiceClient) endpoint.Endpoint {
47 return func(ctx context.Context, request interface{}) (interface{}, error) {
48 req := request.(addendpoint.SumRequest)
49 reply, err := client.Sum(int64(req.A), int64(req.B))
50 if err == service.ErrIntOverflow {
51 return nil, err // special case; see comment on ErrIntOverflow
52 }
53 return addendpoint.SumResponse{V: int(reply.Value), Err: err}, nil
54 }
55 }
56
57 // MakeThriftConcatEndpoint returns an endpoint that invokes the passed Thrift
58 // client. Useful only in clients, and only until a proper
59 // transport/thrift.Client exists.
60 func MakeThriftConcatEndpoint(client *thriftadd.AddServiceClient) endpoint.Endpoint {
61 return func(ctx context.Context, request interface{}) (interface{}, error) {
62 req := request.(addendpoint.ConcatRequest)
63 reply, err := client.Concat(req.A, req.B)
64 return addendpoint.ConcatResponse{V: reply.Value, Err: err}, nil
65 }
66 }
0 struct SumReply {
1 1: i64 value
2 2: string err
3 }
4
5 struct ConcatReply {
6 1: string value
7 2: string err
8 }
9
10 service AddService {
11 SumReply Sum(1: i64 a, 2: i64 b)
12 ConcatReply Concat(1: string a, 2: string b)
13 }
0 #!/usr/bin/env sh
1
2 # See also https://thrift.apache.org/tutorial/go
3
4 thrift -r --gen "go:package_prefix=github.com/go-kit/kit/examples/addsvc2/thrift/gen-go/,thrift_import=github.com/apache/thrift/lib/go/thrift" addsvc.thrift
0 // Autogenerated by Thrift Compiler (0.9.3)
1 // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
2
3 package main
4
5 import (
6 "flag"
7 "fmt"
8 "github.com/apache/thrift/lib/go/thrift"
9 "github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc"
10 "math"
11 "net"
12 "net/url"
13 "os"
14 "strconv"
15 "strings"
16 )
17
18 func Usage() {
19 fmt.Fprintln(os.Stderr, "Usage of ", os.Args[0], " [-h host:port] [-u url] [-f[ramed]] function [arg1 [arg2...]]:")
20 flag.PrintDefaults()
21 fmt.Fprintln(os.Stderr, "\nFunctions:")
22 fmt.Fprintln(os.Stderr, " SumReply Sum(i64 a, i64 b)")
23 fmt.Fprintln(os.Stderr, " ConcatReply Concat(string a, string b)")
24 fmt.Fprintln(os.Stderr)
25 os.Exit(0)
26 }
27
28 func main() {
29 flag.Usage = Usage
30 var host string
31 var port int
32 var protocol string
33 var urlString string
34 var framed bool
35 var useHttp bool
36 var parsedUrl url.URL
37 var trans thrift.TTransport
38 _ = strconv.Atoi
39 _ = math.Abs
40 flag.Usage = Usage
41 flag.StringVar(&host, "h", "localhost", "Specify host and port")
42 flag.IntVar(&port, "p", 9090, "Specify port")
43 flag.StringVar(&protocol, "P", "binary", "Specify the protocol (binary, compact, simplejson, json)")
44 flag.StringVar(&urlString, "u", "", "Specify the url")
45 flag.BoolVar(&framed, "framed", false, "Use framed transport")
46 flag.BoolVar(&useHttp, "http", false, "Use http")
47 flag.Parse()
48
49 if len(urlString) > 0 {
50 parsedUrl, err := url.Parse(urlString)
51 if err != nil {
52 fmt.Fprintln(os.Stderr, "Error parsing URL: ", err)
53 flag.Usage()
54 }
55 host = parsedUrl.Host
56 useHttp = len(parsedUrl.Scheme) <= 0 || parsedUrl.Scheme == "http"
57 } else if useHttp {
58 _, err := url.Parse(fmt.Sprint("http://", host, ":", port))
59 if err != nil {
60 fmt.Fprintln(os.Stderr, "Error parsing URL: ", err)
61 flag.Usage()
62 }
63 }
64
65 cmd := flag.Arg(0)
66 var err error
67 if useHttp {
68 trans, err = thrift.NewTHttpClient(parsedUrl.String())
69 } else {
70 portStr := fmt.Sprint(port)
71 if strings.Contains(host, ":") {
72 host, portStr, err = net.SplitHostPort(host)
73 if err != nil {
74 fmt.Fprintln(os.Stderr, "error with host:", err)
75 os.Exit(1)
76 }
77 }
78 trans, err = thrift.NewTSocket(net.JoinHostPort(host, portStr))
79 if err != nil {
80 fmt.Fprintln(os.Stderr, "error resolving address:", err)
81 os.Exit(1)
82 }
83 if framed {
84 trans = thrift.NewTFramedTransport(trans)
85 }
86 }
87 if err != nil {
88 fmt.Fprintln(os.Stderr, "Error creating transport", err)
89 os.Exit(1)
90 }
91 defer trans.Close()
92 var protocolFactory thrift.TProtocolFactory
93 switch protocol {
94 case "compact":
95 protocolFactory = thrift.NewTCompactProtocolFactory()
96 break
97 case "simplejson":
98 protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
99 break
100 case "json":
101 protocolFactory = thrift.NewTJSONProtocolFactory()
102 break
103 case "binary", "":
104 protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
105 break
106 default:
107 fmt.Fprintln(os.Stderr, "Invalid protocol specified: ", protocol)
108 Usage()
109 os.Exit(1)
110 }
111 client := addsvc.NewAddServiceClientFactory(trans, protocolFactory)
112 if err := trans.Open(); err != nil {
113 fmt.Fprintln(os.Stderr, "Error opening socket to ", host, ":", port, " ", err)
114 os.Exit(1)
115 }
116
117 switch cmd {
118 case "Sum":
119 if flag.NArg()-1 != 2 {
120 fmt.Fprintln(os.Stderr, "Sum requires 2 args")
121 flag.Usage()
122 }
123 argvalue0, err6 := (strconv.ParseInt(flag.Arg(1), 10, 64))
124 if err6 != nil {
125 Usage()
126 return
127 }
128 value0 := argvalue0
129 argvalue1, err7 := (strconv.ParseInt(flag.Arg(2), 10, 64))
130 if err7 != nil {
131 Usage()
132 return
133 }
134 value1 := argvalue1
135 fmt.Print(client.Sum(value0, value1))
136 fmt.Print("\n")
137 break
138 case "Concat":
139 if flag.NArg()-1 != 2 {
140 fmt.Fprintln(os.Stderr, "Concat requires 2 args")
141 flag.Usage()
142 }
143 argvalue0 := flag.Arg(1)
144 value0 := argvalue0
145 argvalue1 := flag.Arg(2)
146 value1 := argvalue1
147 fmt.Print(client.Concat(value0, value1))
148 fmt.Print("\n")
149 break
150 case "":
151 Usage()
152 break
153 default:
154 fmt.Fprintln(os.Stderr, "Invalid function ", cmd)
155 }
156 }
0 // Autogenerated by Thrift Compiler (0.9.3)
1 // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
2
3 package addsvc
4
5 import (
6 "bytes"
7 "fmt"
8 "github.com/apache/thrift/lib/go/thrift"
9 )
10
11 // (needed to ensure safety because of naive import list construction.)
12 var _ = thrift.ZERO
13 var _ = fmt.Printf
14 var _ = bytes.Equal
15
16 type AddService interface {
17 // Parameters:
18 // - A
19 // - B
20 Sum(a int64, b int64) (r *SumReply, err error)
21 // Parameters:
22 // - A
23 // - B
24 Concat(a string, b string) (r *ConcatReply, err error)
25 }
26
27 type AddServiceClient struct {
28 Transport thrift.TTransport
29 ProtocolFactory thrift.TProtocolFactory
30 InputProtocol thrift.TProtocol
31 OutputProtocol thrift.TProtocol
32 SeqId int32
33 }
34
35 func NewAddServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *AddServiceClient {
36 return &AddServiceClient{Transport: t,
37 ProtocolFactory: f,
38 InputProtocol: f.GetProtocol(t),
39 OutputProtocol: f.GetProtocol(t),
40 SeqId: 0,
41 }
42 }
43
44 func NewAddServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *AddServiceClient {
45 return &AddServiceClient{Transport: t,
46 ProtocolFactory: nil,
47 InputProtocol: iprot,
48 OutputProtocol: oprot,
49 SeqId: 0,
50 }
51 }
52
53 // Parameters:
54 // - A
55 // - B
56 func (p *AddServiceClient) Sum(a int64, b int64) (r *SumReply, err error) {
57 if err = p.sendSum(a, b); err != nil {
58 return
59 }
60 return p.recvSum()
61 }
62
63 func (p *AddServiceClient) sendSum(a int64, b int64) (err error) {
64 oprot := p.OutputProtocol
65 if oprot == nil {
66 oprot = p.ProtocolFactory.GetProtocol(p.Transport)
67 p.OutputProtocol = oprot
68 }
69 p.SeqId++
70 if err = oprot.WriteMessageBegin("Sum", thrift.CALL, p.SeqId); err != nil {
71 return
72 }
73 args := AddServiceSumArgs{
74 A: a,
75 B: b,
76 }
77 if err = args.Write(oprot); err != nil {
78 return
79 }
80 if err = oprot.WriteMessageEnd(); err != nil {
81 return
82 }
83 return oprot.Flush()
84 }
85
86 func (p *AddServiceClient) recvSum() (value *SumReply, err error) {
87 iprot := p.InputProtocol
88 if iprot == nil {
89 iprot = p.ProtocolFactory.GetProtocol(p.Transport)
90 p.InputProtocol = iprot
91 }
92 method, mTypeId, seqId, err := iprot.ReadMessageBegin()
93 if err != nil {
94 return
95 }
96 if method != "Sum" {
97 err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "Sum failed: wrong method name")
98 return
99 }
100 if p.SeqId != seqId {
101 err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "Sum failed: out of sequence response")
102 return
103 }
104 if mTypeId == thrift.EXCEPTION {
105 error0 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception")
106 var error1 error
107 error1, err = error0.Read(iprot)
108 if err != nil {
109 return
110 }
111 if err = iprot.ReadMessageEnd(); err != nil {
112 return
113 }
114 err = error1
115 return
116 }
117 if mTypeId != thrift.REPLY {
118 err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "Sum failed: invalid message type")
119 return
120 }
121 result := AddServiceSumResult{}
122 if err = result.Read(iprot); err != nil {
123 return
124 }
125 if err = iprot.ReadMessageEnd(); err != nil {
126 return
127 }
128 value = result.GetSuccess()
129 return
130 }
131
132 // Parameters:
133 // - A
134 // - B
135 func (p *AddServiceClient) Concat(a string, b string) (r *ConcatReply, err error) {
136 if err = p.sendConcat(a, b); err != nil {
137 return
138 }
139 return p.recvConcat()
140 }
141
142 func (p *AddServiceClient) sendConcat(a string, b string) (err error) {
143 oprot := p.OutputProtocol
144 if oprot == nil {
145 oprot = p.ProtocolFactory.GetProtocol(p.Transport)
146 p.OutputProtocol = oprot
147 }
148 p.SeqId++
149 if err = oprot.WriteMessageBegin("Concat", thrift.CALL, p.SeqId); err != nil {
150 return
151 }
152 args := AddServiceConcatArgs{
153 A: a,
154 B: b,
155 }
156 if err = args.Write(oprot); err != nil {
157 return
158 }
159 if err = oprot.WriteMessageEnd(); err != nil {
160 return
161 }
162 return oprot.Flush()
163 }
164
165 func (p *AddServiceClient) recvConcat() (value *ConcatReply, err error) {
166 iprot := p.InputProtocol
167 if iprot == nil {
168 iprot = p.ProtocolFactory.GetProtocol(p.Transport)
169 p.InputProtocol = iprot
170 }
171 method, mTypeId, seqId, err := iprot.ReadMessageBegin()
172 if err != nil {
173 return
174 }
175 if method != "Concat" {
176 err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "Concat failed: wrong method name")
177 return
178 }
179 if p.SeqId != seqId {
180 err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "Concat failed: out of sequence response")
181 return
182 }
183 if mTypeId == thrift.EXCEPTION {
184 error2 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception")
185 var error3 error
186 error3, err = error2.Read(iprot)
187 if err != nil {
188 return
189 }
190 if err = iprot.ReadMessageEnd(); err != nil {
191 return
192 }
193 err = error3
194 return
195 }
196 if mTypeId != thrift.REPLY {
197 err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "Concat failed: invalid message type")
198 return
199 }
200 result := AddServiceConcatResult{}
201 if err = result.Read(iprot); err != nil {
202 return
203 }
204 if err = iprot.ReadMessageEnd(); err != nil {
205 return
206 }
207 value = result.GetSuccess()
208 return
209 }
210
211 type AddServiceProcessor struct {
212 processorMap map[string]thrift.TProcessorFunction
213 handler AddService
214 }
215
216 func (p *AddServiceProcessor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) {
217 p.processorMap[key] = processor
218 }
219
220 func (p *AddServiceProcessor) GetProcessorFunction(key string) (processor thrift.TProcessorFunction, ok bool) {
221 processor, ok = p.processorMap[key]
222 return processor, ok
223 }
224
225 func (p *AddServiceProcessor) ProcessorMap() map[string]thrift.TProcessorFunction {
226 return p.processorMap
227 }
228
229 func NewAddServiceProcessor(handler AddService) *AddServiceProcessor {
230
231 self4 := &AddServiceProcessor{handler: handler, processorMap: make(map[string]thrift.TProcessorFunction)}
232 self4.processorMap["Sum"] = &addServiceProcessorSum{handler: handler}
233 self4.processorMap["Concat"] = &addServiceProcessorConcat{handler: handler}
234 return self4
235 }
236
237 func (p *AddServiceProcessor) Process(iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
238 name, _, seqId, err := iprot.ReadMessageBegin()
239 if err != nil {
240 return false, err
241 }
242 if processor, ok := p.GetProcessorFunction(name); ok {
243 return processor.Process(seqId, iprot, oprot)
244 }
245 iprot.Skip(thrift.STRUCT)
246 iprot.ReadMessageEnd()
247 x5 := thrift.NewTApplicationException(thrift.UNKNOWN_METHOD, "Unknown function "+name)
248 oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId)
249 x5.Write(oprot)
250 oprot.WriteMessageEnd()
251 oprot.Flush()
252 return false, x5
253
254 }
255
256 type addServiceProcessorSum struct {
257 handler AddService
258 }
259
260 func (p *addServiceProcessorSum) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
261 args := AddServiceSumArgs{}
262 if err = args.Read(iprot); err != nil {
263 iprot.ReadMessageEnd()
264 x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
265 oprot.WriteMessageBegin("Sum", thrift.EXCEPTION, seqId)
266 x.Write(oprot)
267 oprot.WriteMessageEnd()
268 oprot.Flush()
269 return false, err
270 }
271
272 iprot.ReadMessageEnd()
273 result := AddServiceSumResult{}
274 var retval *SumReply
275 var err2 error
276 if retval, err2 = p.handler.Sum(args.A, args.B); err2 != nil {
277 x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing Sum: "+err2.Error())
278 oprot.WriteMessageBegin("Sum", thrift.EXCEPTION, seqId)
279 x.Write(oprot)
280 oprot.WriteMessageEnd()
281 oprot.Flush()
282 return true, err2
283 } else {
284 result.Success = retval
285 }
286 if err2 = oprot.WriteMessageBegin("Sum", thrift.REPLY, seqId); err2 != nil {
287 err = err2
288 }
289 if err2 = result.Write(oprot); err == nil && err2 != nil {
290 err = err2
291 }
292 if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
293 err = err2
294 }
295 if err2 = oprot.Flush(); err == nil && err2 != nil {
296 err = err2
297 }
298 if err != nil {
299 return
300 }
301 return true, err
302 }
303
304 type addServiceProcessorConcat struct {
305 handler AddService
306 }
307
308 func (p *addServiceProcessorConcat) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
309 args := AddServiceConcatArgs{}
310 if err = args.Read(iprot); err != nil {
311 iprot.ReadMessageEnd()
312 x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
313 oprot.WriteMessageBegin("Concat", thrift.EXCEPTION, seqId)
314 x.Write(oprot)
315 oprot.WriteMessageEnd()
316 oprot.Flush()
317 return false, err
318 }
319
320 iprot.ReadMessageEnd()
321 result := AddServiceConcatResult{}
322 var retval *ConcatReply
323 var err2 error
324 if retval, err2 = p.handler.Concat(args.A, args.B); err2 != nil {
325 x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing Concat: "+err2.Error())
326 oprot.WriteMessageBegin("Concat", thrift.EXCEPTION, seqId)
327 x.Write(oprot)
328 oprot.WriteMessageEnd()
329 oprot.Flush()
330 return true, err2
331 } else {
332 result.Success = retval
333 }
334 if err2 = oprot.WriteMessageBegin("Concat", thrift.REPLY, seqId); err2 != nil {
335 err = err2
336 }
337 if err2 = result.Write(oprot); err == nil && err2 != nil {
338 err = err2
339 }
340 if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
341 err = err2
342 }
343 if err2 = oprot.Flush(); err == nil && err2 != nil {
344 err = err2
345 }
346 if err != nil {
347 return
348 }
349 return true, err
350 }
351
352 // HELPER FUNCTIONS AND STRUCTURES
353
354 // Attributes:
355 // - A
356 // - B
357 type AddServiceSumArgs struct {
358 A int64 `thrift:"a,1" json:"a"`
359 B int64 `thrift:"b,2" json:"b"`
360 }
361
362 func NewAddServiceSumArgs() *AddServiceSumArgs {
363 return &AddServiceSumArgs{}
364 }
365
366 func (p *AddServiceSumArgs) GetA() int64 {
367 return p.A
368 }
369
370 func (p *AddServiceSumArgs) GetB() int64 {
371 return p.B
372 }
373 func (p *AddServiceSumArgs) Read(iprot thrift.TProtocol) error {
374 if _, err := iprot.ReadStructBegin(); err != nil {
375 return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
376 }
377
378 for {
379 _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
380 if err != nil {
381 return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
382 }
383 if fieldTypeId == thrift.STOP {
384 break
385 }
386 switch fieldId {
387 case 1:
388 if err := p.readField1(iprot); err != nil {
389 return err
390 }
391 case 2:
392 if err := p.readField2(iprot); err != nil {
393 return err
394 }
395 default:
396 if err := iprot.Skip(fieldTypeId); err != nil {
397 return err
398 }
399 }
400 if err := iprot.ReadFieldEnd(); err != nil {
401 return err
402 }
403 }
404 if err := iprot.ReadStructEnd(); err != nil {
405 return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
406 }
407 return nil
408 }
409
410 func (p *AddServiceSumArgs) readField1(iprot thrift.TProtocol) error {
411 if v, err := iprot.ReadI64(); err != nil {
412 return thrift.PrependError("error reading field 1: ", err)
413 } else {
414 p.A = v
415 }
416 return nil
417 }
418
419 func (p *AddServiceSumArgs) readField2(iprot thrift.TProtocol) error {
420 if v, err := iprot.ReadI64(); err != nil {
421 return thrift.PrependError("error reading field 2: ", err)
422 } else {
423 p.B = v
424 }
425 return nil
426 }
427
428 func (p *AddServiceSumArgs) Write(oprot thrift.TProtocol) error {
429 if err := oprot.WriteStructBegin("Sum_args"); err != nil {
430 return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
431 }
432 if err := p.writeField1(oprot); err != nil {
433 return err
434 }
435 if err := p.writeField2(oprot); err != nil {
436 return err
437 }
438 if err := oprot.WriteFieldStop(); err != nil {
439 return thrift.PrependError("write field stop error: ", err)
440 }
441 if err := oprot.WriteStructEnd(); err != nil {
442 return thrift.PrependError("write struct stop error: ", err)
443 }
444 return nil
445 }
446
447 func (p *AddServiceSumArgs) writeField1(oprot thrift.TProtocol) (err error) {
448 if err := oprot.WriteFieldBegin("a", thrift.I64, 1); err != nil {
449 return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:a: ", p), err)
450 }
451 if err := oprot.WriteI64(int64(p.A)); err != nil {
452 return thrift.PrependError(fmt.Sprintf("%T.a (1) field write error: ", p), err)
453 }
454 if err := oprot.WriteFieldEnd(); err != nil {
455 return thrift.PrependError(fmt.Sprintf("%T write field end error 1:a: ", p), err)
456 }
457 return err
458 }
459
460 func (p *AddServiceSumArgs) writeField2(oprot thrift.TProtocol) (err error) {
461 if err := oprot.WriteFieldBegin("b", thrift.I64, 2); err != nil {
462 return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:b: ", p), err)
463 }
464 if err := oprot.WriteI64(int64(p.B)); err != nil {
465 return thrift.PrependError(fmt.Sprintf("%T.b (2) field write error: ", p), err)
466 }
467 if err := oprot.WriteFieldEnd(); err != nil {
468 return thrift.PrependError(fmt.Sprintf("%T write field end error 2:b: ", p), err)
469 }
470 return err
471 }
472
473 func (p *AddServiceSumArgs) String() string {
474 if p == nil {
475 return "<nil>"
476 }
477 return fmt.Sprintf("AddServiceSumArgs(%+v)", *p)
478 }
479
480 // Attributes:
481 // - Success
482 type AddServiceSumResult struct {
483 Success *SumReply `thrift:"success,0" json:"success,omitempty"`
484 }
485
486 func NewAddServiceSumResult() *AddServiceSumResult {
487 return &AddServiceSumResult{}
488 }
489
490 var AddServiceSumResult_Success_DEFAULT *SumReply
491
492 func (p *AddServiceSumResult) GetSuccess() *SumReply {
493 if !p.IsSetSuccess() {
494 return AddServiceSumResult_Success_DEFAULT
495 }
496 return p.Success
497 }
498 func (p *AddServiceSumResult) IsSetSuccess() bool {
499 return p.Success != nil
500 }
501
502 func (p *AddServiceSumResult) Read(iprot thrift.TProtocol) error {
503 if _, err := iprot.ReadStructBegin(); err != nil {
504 return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
505 }
506
507 for {
508 _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
509 if err != nil {
510 return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
511 }
512 if fieldTypeId == thrift.STOP {
513 break
514 }
515 switch fieldId {
516 case 0:
517 if err := p.readField0(iprot); err != nil {
518 return err
519 }
520 default:
521 if err := iprot.Skip(fieldTypeId); err != nil {
522 return err
523 }
524 }
525 if err := iprot.ReadFieldEnd(); err != nil {
526 return err
527 }
528 }
529 if err := iprot.ReadStructEnd(); err != nil {
530 return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
531 }
532 return nil
533 }
534
535 func (p *AddServiceSumResult) readField0(iprot thrift.TProtocol) error {
536 p.Success = &SumReply{}
537 if err := p.Success.Read(iprot); err != nil {
538 return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
539 }
540 return nil
541 }
542
543 func (p *AddServiceSumResult) Write(oprot thrift.TProtocol) error {
544 if err := oprot.WriteStructBegin("Sum_result"); err != nil {
545 return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
546 }
547 if err := p.writeField0(oprot); err != nil {
548 return err
549 }
550 if err := oprot.WriteFieldStop(); err != nil {
551 return thrift.PrependError("write field stop error: ", err)
552 }
553 if err := oprot.WriteStructEnd(); err != nil {
554 return thrift.PrependError("write struct stop error: ", err)
555 }
556 return nil
557 }
558
559 func (p *AddServiceSumResult) writeField0(oprot thrift.TProtocol) (err error) {
560 if p.IsSetSuccess() {
561 if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
562 return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err)
563 }
564 if err := p.Success.Write(oprot); err != nil {
565 return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
566 }
567 if err := oprot.WriteFieldEnd(); err != nil {
568 return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err)
569 }
570 }
571 return err
572 }
573
574 func (p *AddServiceSumResult) String() string {
575 if p == nil {
576 return "<nil>"
577 }
578 return fmt.Sprintf("AddServiceSumResult(%+v)", *p)
579 }
580
581 // Attributes:
582 // - A
583 // - B
584 type AddServiceConcatArgs struct {
585 A string `thrift:"a,1" json:"a"`
586 B string `thrift:"b,2" json:"b"`
587 }
588
589 func NewAddServiceConcatArgs() *AddServiceConcatArgs {
590 return &AddServiceConcatArgs{}
591 }
592
593 func (p *AddServiceConcatArgs) GetA() string {
594 return p.A
595 }
596
597 func (p *AddServiceConcatArgs) GetB() string {
598 return p.B
599 }
600 func (p *AddServiceConcatArgs) Read(iprot thrift.TProtocol) error {
601 if _, err := iprot.ReadStructBegin(); err != nil {
602 return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
603 }
604
605 for {
606 _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
607 if err != nil {
608 return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
609 }
610 if fieldTypeId == thrift.STOP {
611 break
612 }
613 switch fieldId {
614 case 1:
615 if err := p.readField1(iprot); err != nil {
616 return err
617 }
618 case 2:
619 if err := p.readField2(iprot); err != nil {
620 return err
621 }
622 default:
623 if err := iprot.Skip(fieldTypeId); err != nil {
624 return err
625 }
626 }
627 if err := iprot.ReadFieldEnd(); err != nil {
628 return err
629 }
630 }
631 if err := iprot.ReadStructEnd(); err != nil {
632 return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
633 }
634 return nil
635 }
636
637 func (p *AddServiceConcatArgs) readField1(iprot thrift.TProtocol) error {
638 if v, err := iprot.ReadString(); err != nil {
639 return thrift.PrependError("error reading field 1: ", err)
640 } else {
641 p.A = v
642 }
643 return nil
644 }
645
646 func (p *AddServiceConcatArgs) readField2(iprot thrift.TProtocol) error {
647 if v, err := iprot.ReadString(); err != nil {
648 return thrift.PrependError("error reading field 2: ", err)
649 } else {
650 p.B = v
651 }
652 return nil
653 }
654
655 func (p *AddServiceConcatArgs) Write(oprot thrift.TProtocol) error {
656 if err := oprot.WriteStructBegin("Concat_args"); err != nil {
657 return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
658 }
659 if err := p.writeField1(oprot); err != nil {
660 return err
661 }
662 if err := p.writeField2(oprot); err != nil {
663 return err
664 }
665 if err := oprot.WriteFieldStop(); err != nil {
666 return thrift.PrependError("write field stop error: ", err)
667 }
668 if err := oprot.WriteStructEnd(); err != nil {
669 return thrift.PrependError("write struct stop error: ", err)
670 }
671 return nil
672 }
673
674 func (p *AddServiceConcatArgs) writeField1(oprot thrift.TProtocol) (err error) {
675 if err := oprot.WriteFieldBegin("a", thrift.STRING, 1); err != nil {
676 return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:a: ", p), err)
677 }
678 if err := oprot.WriteString(string(p.A)); err != nil {
679 return thrift.PrependError(fmt.Sprintf("%T.a (1) field write error: ", p), err)
680 }
681 if err := oprot.WriteFieldEnd(); err != nil {
682 return thrift.PrependError(fmt.Sprintf("%T write field end error 1:a: ", p), err)
683 }
684 return err
685 }
686
687 func (p *AddServiceConcatArgs) writeField2(oprot thrift.TProtocol) (err error) {
688 if err := oprot.WriteFieldBegin("b", thrift.STRING, 2); err != nil {
689 return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:b: ", p), err)
690 }
691 if err := oprot.WriteString(string(p.B)); err != nil {
692 return thrift.PrependError(fmt.Sprintf("%T.b (2) field write error: ", p), err)
693 }
694 if err := oprot.WriteFieldEnd(); err != nil {
695 return thrift.PrependError(fmt.Sprintf("%T write field end error 2:b: ", p), err)
696 }
697 return err
698 }
699
700 func (p *AddServiceConcatArgs) String() string {
701 if p == nil {
702 return "<nil>"
703 }
704 return fmt.Sprintf("AddServiceConcatArgs(%+v)", *p)
705 }
706
707 // Attributes:
708 // - Success
709 type AddServiceConcatResult struct {
710 Success *ConcatReply `thrift:"success,0" json:"success,omitempty"`
711 }
712
713 func NewAddServiceConcatResult() *AddServiceConcatResult {
714 return &AddServiceConcatResult{}
715 }
716
717 var AddServiceConcatResult_Success_DEFAULT *ConcatReply
718
719 func (p *AddServiceConcatResult) GetSuccess() *ConcatReply {
720 if !p.IsSetSuccess() {
721 return AddServiceConcatResult_Success_DEFAULT
722 }
723 return p.Success
724 }
725 func (p *AddServiceConcatResult) IsSetSuccess() bool {
726 return p.Success != nil
727 }
728
729 func (p *AddServiceConcatResult) Read(iprot thrift.TProtocol) error {
730 if _, err := iprot.ReadStructBegin(); err != nil {
731 return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
732 }
733
734 for {
735 _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
736 if err != nil {
737 return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
738 }
739 if fieldTypeId == thrift.STOP {
740 break
741 }
742 switch fieldId {
743 case 0:
744 if err := p.readField0(iprot); err != nil {
745 return err
746 }
747 default:
748 if err := iprot.Skip(fieldTypeId); err != nil {
749 return err
750 }
751 }
752 if err := iprot.ReadFieldEnd(); err != nil {
753 return err
754 }
755 }
756 if err := iprot.ReadStructEnd(); err != nil {
757 return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
758 }
759 return nil
760 }
761
762 func (p *AddServiceConcatResult) readField0(iprot thrift.TProtocol) error {
763 p.Success = &ConcatReply{}
764 if err := p.Success.Read(iprot); err != nil {
765 return thrift.PrependError(fmt.Sprintf("%T error reading struct: ", p.Success), err)
766 }
767 return nil
768 }
769
770 func (p *AddServiceConcatResult) Write(oprot thrift.TProtocol) error {
771 if err := oprot.WriteStructBegin("Concat_result"); err != nil {
772 return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
773 }
774 if err := p.writeField0(oprot); err != nil {
775 return err
776 }
777 if err := oprot.WriteFieldStop(); err != nil {
778 return thrift.PrependError("write field stop error: ", err)
779 }
780 if err := oprot.WriteStructEnd(); err != nil {
781 return thrift.PrependError("write struct stop error: ", err)
782 }
783 return nil
784 }
785
786 func (p *AddServiceConcatResult) writeField0(oprot thrift.TProtocol) (err error) {
787 if p.IsSetSuccess() {
788 if err := oprot.WriteFieldBegin("success", thrift.STRUCT, 0); err != nil {
789 return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err)
790 }
791 if err := p.Success.Write(oprot); err != nil {
792 return thrift.PrependError(fmt.Sprintf("%T error writing struct: ", p.Success), err)
793 }
794 if err := oprot.WriteFieldEnd(); err != nil {
795 return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err)
796 }
797 }
798 return err
799 }
800
801 func (p *AddServiceConcatResult) String() string {
802 if p == nil {
803 return "<nil>"
804 }
805 return fmt.Sprintf("AddServiceConcatResult(%+v)", *p)
806 }
0 // Autogenerated by Thrift Compiler (0.9.3)
1 // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
2
3 package addsvc
4
5 import (
6 "bytes"
7 "fmt"
8 "github.com/apache/thrift/lib/go/thrift"
9 )
10
11 // (needed to ensure safety because of naive import list construction.)
12 var _ = thrift.ZERO
13 var _ = fmt.Printf
14 var _ = bytes.Equal
15
16 func init() {
17 }
0 // Autogenerated by Thrift Compiler (0.9.3)
1 // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
2
3 package addsvc
4
5 import (
6 "bytes"
7 "fmt"
8 "github.com/apache/thrift/lib/go/thrift"
9 )
10
11 // (needed to ensure safety because of naive import list construction.)
12 var _ = thrift.ZERO
13 var _ = fmt.Printf
14 var _ = bytes.Equal
15
16 var GoUnusedProtection__ int
17
18 // Attributes:
19 // - Value
20 // - Err
21 type SumReply struct {
22 Value int64 `thrift:"value,1" json:"value"`
23 Err string `thrift:"err,2" json:"err"`
24 }
25
26 func NewSumReply() *SumReply {
27 return &SumReply{}
28 }
29
30 func (p *SumReply) GetValue() int64 {
31 return p.Value
32 }
33
34 func (p *SumReply) GetErr() string {
35 return p.Err
36 }
37 func (p *SumReply) Read(iprot thrift.TProtocol) error {
38 if _, err := iprot.ReadStructBegin(); err != nil {
39 return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
40 }
41
42 for {
43 _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
44 if err != nil {
45 return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
46 }
47 if fieldTypeId == thrift.STOP {
48 break
49 }
50 switch fieldId {
51 case 1:
52 if err := p.readField1(iprot); err != nil {
53 return err
54 }
55 case 2:
56 if err := p.readField2(iprot); err != nil {
57 return err
58 }
59 default:
60 if err := iprot.Skip(fieldTypeId); err != nil {
61 return err
62 }
63 }
64 if err := iprot.ReadFieldEnd(); err != nil {
65 return err
66 }
67 }
68 if err := iprot.ReadStructEnd(); err != nil {
69 return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
70 }
71 return nil
72 }
73
74 func (p *SumReply) readField1(iprot thrift.TProtocol) error {
75 if v, err := iprot.ReadI64(); err != nil {
76 return thrift.PrependError("error reading field 1: ", err)
77 } else {
78 p.Value = v
79 }
80 return nil
81 }
82
83 func (p *SumReply) readField2(iprot thrift.TProtocol) error {
84 if v, err := iprot.ReadString(); err != nil {
85 return thrift.PrependError("error reading field 2: ", err)
86 } else {
87 p.Err = v
88 }
89 return nil
90 }
91
92 func (p *SumReply) Write(oprot thrift.TProtocol) error {
93 if err := oprot.WriteStructBegin("SumReply"); err != nil {
94 return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
95 }
96 if err := p.writeField1(oprot); err != nil {
97 return err
98 }
99 if err := p.writeField2(oprot); err != nil {
100 return err
101 }
102 if err := oprot.WriteFieldStop(); err != nil {
103 return thrift.PrependError("write field stop error: ", err)
104 }
105 if err := oprot.WriteStructEnd(); err != nil {
106 return thrift.PrependError("write struct stop error: ", err)
107 }
108 return nil
109 }
110
111 func (p *SumReply) writeField1(oprot thrift.TProtocol) (err error) {
112 if err := oprot.WriteFieldBegin("value", thrift.I64, 1); err != nil {
113 return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err)
114 }
115 if err := oprot.WriteI64(int64(p.Value)); err != nil {
116 return thrift.PrependError(fmt.Sprintf("%T.value (1) field write error: ", p), err)
117 }
118 if err := oprot.WriteFieldEnd(); err != nil {
119 return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err)
120 }
121 return err
122 }
123
124 func (p *SumReply) writeField2(oprot thrift.TProtocol) (err error) {
125 if err := oprot.WriteFieldBegin("err", thrift.STRING, 2); err != nil {
126 return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:err: ", p), err)
127 }
128 if err := oprot.WriteString(string(p.Err)); err != nil {
129 return thrift.PrependError(fmt.Sprintf("%T.err (2) field write error: ", p), err)
130 }
131 if err := oprot.WriteFieldEnd(); err != nil {
132 return thrift.PrependError(fmt.Sprintf("%T write field end error 2:err: ", p), err)
133 }
134 return err
135 }
136
137 func (p *SumReply) String() string {
138 if p == nil {
139 return "<nil>"
140 }
141 return fmt.Sprintf("SumReply(%+v)", *p)
142 }
143
144 // Attributes:
145 // - Value
146 // - Err
147 type ConcatReply struct {
148 Value string `thrift:"value,1" json:"value"`
149 Err string `thrift:"err,2" json:"err"`
150 }
151
152 func NewConcatReply() *ConcatReply {
153 return &ConcatReply{}
154 }
155
156 func (p *ConcatReply) GetValue() string {
157 return p.Value
158 }
159
160 func (p *ConcatReply) GetErr() string {
161 return p.Err
162 }
163 func (p *ConcatReply) Read(iprot thrift.TProtocol) error {
164 if _, err := iprot.ReadStructBegin(); err != nil {
165 return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
166 }
167
168 for {
169 _, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
170 if err != nil {
171 return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
172 }
173 if fieldTypeId == thrift.STOP {
174 break
175 }
176 switch fieldId {
177 case 1:
178 if err := p.readField1(iprot); err != nil {
179 return err
180 }
181 case 2:
182 if err := p.readField2(iprot); err != nil {
183 return err
184 }
185 default:
186 if err := iprot.Skip(fieldTypeId); err != nil {
187 return err
188 }
189 }
190 if err := iprot.ReadFieldEnd(); err != nil {
191 return err
192 }
193 }
194 if err := iprot.ReadStructEnd(); err != nil {
195 return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
196 }
197 return nil
198 }
199
200 func (p *ConcatReply) readField1(iprot thrift.TProtocol) error {
201 if v, err := iprot.ReadString(); err != nil {
202 return thrift.PrependError("error reading field 1: ", err)
203 } else {
204 p.Value = v
205 }
206 return nil
207 }
208
209 func (p *ConcatReply) readField2(iprot thrift.TProtocol) error {
210 if v, err := iprot.ReadString(); err != nil {
211 return thrift.PrependError("error reading field 2: ", err)
212 } else {
213 p.Err = v
214 }
215 return nil
216 }
217
218 func (p *ConcatReply) Write(oprot thrift.TProtocol) error {
219 if err := oprot.WriteStructBegin("ConcatReply"); err != nil {
220 return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
221 }
222 if err := p.writeField1(oprot); err != nil {
223 return err
224 }
225 if err := p.writeField2(oprot); err != nil {
226 return err
227 }
228 if err := oprot.WriteFieldStop(); err != nil {
229 return thrift.PrependError("write field stop error: ", err)
230 }
231 if err := oprot.WriteStructEnd(); err != nil {
232 return thrift.PrependError("write struct stop error: ", err)
233 }
234 return nil
235 }
236
237 func (p *ConcatReply) writeField1(oprot thrift.TProtocol) (err error) {
238 if err := oprot.WriteFieldBegin("value", thrift.STRING, 1); err != nil {
239 return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:value: ", p), err)
240 }
241 if err := oprot.WriteString(string(p.Value)); err != nil {
242 return thrift.PrependError(fmt.Sprintf("%T.value (1) field write error: ", p), err)
243 }
244 if err := oprot.WriteFieldEnd(); err != nil {
245 return thrift.PrependError(fmt.Sprintf("%T write field end error 1:value: ", p), err)
246 }
247 return err
248 }
249
250 func (p *ConcatReply) writeField2(oprot thrift.TProtocol) (err error) {
251 if err := oprot.WriteFieldBegin("err", thrift.STRING, 2); err != nil {
252 return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:err: ", p), err)
253 }
254 if err := oprot.WriteString(string(p.Err)); err != nil {
255 return thrift.PrependError(fmt.Sprintf("%T.err (2) field write error: ", p), err)
256 }
257 if err := oprot.WriteFieldEnd(); err != nil {
258 return thrift.PrependError(fmt.Sprintf("%T write field end error 2:err: ", p), err)
259 }
260 return err
261 }
262
263 func (p *ConcatReply) String() string {
264 if p == nil {
265 return "<nil>"
266 }
267 return fmt.Sprintf("ConcatReply(%+v)", *p)
268 }