Open a gRPC connection to a service

Function to create a new gRPC connection.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample


import (


// NewConn creates a new gRPC connection.
// host should be of the form domain:port, e.g.,
func NewConn(host string, insecure bool) (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	if host != "" {
		opts = append(opts, grpc.WithAuthority(host))

	if insecure {
		opts = append(opts, grpc.WithInsecure())
	} else {
		systemRoots, err := x509.SystemCertPool()
		if err != nil {
			return nil, err
		cred := credentials.NewTLS(&tls.Config{
			RootCAs: systemRoots,
		opts = append(opts, grpc.WithTransportCredentials(cred))

	return grpc.Dial(host, opts...)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.