Distributed programming: Difference between revisions

(→‎{{header|Go}}: add gRPC)
(→‎{{header|Go}}: add Thrift)
Line 639:
<pre>
Tax on 300 cents is 15 cents
</pre>
 
===Apache Thrift===
See https://thrift.apache.org/
 
'''.thrift'''
 
Like gRPC, Thrift requires a language independent interface definition file:
<lang thrift>service TaxService {
i32 tax(1: i32 amt)
}</lang>
'''Server:'''
<lang go>package main
 
import (
"errors"
"log"
 
"git.apache.org/thrift.git/lib/go/thrift"
 
"gen-go/tax"
)
 
type taxHandler float64
 
func (r taxHandler) Tax(amt int32) (int32, error) {
if amt < 0 {
return 0, errors.New("Negative amounts not allowed")
}
return int32(float64(amt)*float64(r) + .5), nil
}
 
func main() {
transport, err := thrift.NewTServerSocket("localhost:3141")
if err != nil {
log.Fatal(err)
}
transFac := thrift.NewTTransportFactory()
protoFac := thrift.NewTCompactProtocolFactory()
proc := tax.NewTaxServiceProcessor(taxHandler(.05))
s := thrift.NewTSimpleServer4(proc, transport, transFac, protoFac)
if err := s.Serve(); err != nil {
log.Fatal(err)
}
}</lang>
'''Client:'''
<lang go>package main
 
import (
"fmt"
"log"
 
"git.apache.org/thrift.git/lib/go/thrift"
 
"gen-go/tax"
)
 
func main() {
transport, err := thrift.NewTSocket("localhost:3141")
if err != nil {
log.Fatal(err)
}
if err := transport.Open(); err != nil {
log.Fatal(err)
}
protoFac := thrift.NewTCompactProtocolFactory()
client := tax.NewTaxServiceClientFactory(transport, protoFac)
amt := int32(300)
t, err := client.Tax(amt)
if err != nil {
log.Print(err)
} else {
fmt.Println("tax on", amt, "is", t)
}
transport.Close()
}</lang>
{{out | Client output}}
<pre>
tax on 300 is 15
</pre>
 
1,707

edits