Skip to content

Instantly share code, notes, and snippets.

@f3nry
Last active February 12, 2019 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f3nry/816a7a0ada7bfcd883a9bf36119eba5d to your computer and use it in GitHub Desktop.
Save f3nry/816a7a0ada7bfcd883a9bf36119eba5d to your computer and use it in GitHub Desktop.
Simple Go gRPC Client
package main
import (
"context"
"flag"
"fmt"
"log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"api"
)
var (
tls = flag.Bool("tls", true, "Connection uses TLS if true, else plain TCP")
caFile = flag.String("ca_file", "", "The file containning the CA root cert file")
serverAddr = flag.String("server_addr", "<api-gateway-host>:443", "The server address in the format of host:port")
serverHostOverride = flag.String("server_host_override", "<api-gateway-host>", "The server name use to verify the hostname returned by TLS handshake")
)
func main() {
flag.Parse()
var opts []grpc.DialOption
if *tls {
creds, err := credentials.NewClientTLSFromFile(*caFile, *serverHostOverride)
if err != nil {
log.Fatalf("Failed to create TLS credentials %v", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
opts = append(opts, grpc.WithWaitForHandshake())
} else {
opts = append(opts, grpc.WithInsecure())
}
conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := api.NewProdClient(conn)
resp, err := client.Alive(context.TODO(), &api.AliveRequest{Message: "Hello"})
if err != nil {
log.Fatalf("err making request: %v", err)
}
fmt.Println(resp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment