Skip to content

Instantly share code, notes, and snippets.

@mayankcpdixit
Last active April 23, 2021 13:25
Show Gist options
  • Save mayankcpdixit/d2260431de5d2a1b2569bace1716f2af to your computer and use it in GitHub Desktop.
Save mayankcpdixit/d2260431de5d2a1b2569bace1716f2af to your computer and use it in GitHub Desktop.
Using TLS in grpc-gateway

Using TLS in grpc-gateway

In GRPC client

By default DialOption{grpc.WithInsecure()} is used in example. And as docs mention you just need to replace WithInsecure with transport creds.

//opts := []grpc.DialOption{grpc.WithInsecure()}
creds, _ := credentials.NewClientTLSFromFile("tls.crt", "")
opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}

In HTTP server

Replace ListenAndServe to ListenAndServeTLS

Full example:

func run() error {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	mux := runtime.NewServeMux()
	// opts := []grpc.DialOption{grpc.WithInsecure()}
	creds, err := credentials.NewClientTLSFromFile("tls.crt", "")
	if err != nil {
		return err
	}

	opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}
	err = fw.RegisterUserServiceHandlerFromEndpoint(ctx, mux, *grpcTarget, opts)
	if err != nil {
		return err
	}
	return http.ListenAndServeTLS(*hostAddr, "tls.crt", "tls.key", mux)
}

PS: blog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment