How do I use TLS with gRPC in Go?

Using TLS (Transport Layer Security) with gRPC in Go is essential for ensuring secure communication between clients and servers. This guide will demonstrate how to set up a simple gRPC server and client with TLS support.

gRPC, Go, TLS, Transport Layer Security, secure communication, gRPC server, gRPC client

This tutorial explains how to implement TLS with gRPC in Go, enhancing security in your applications.

Example Code


package main

import (
    "log"
    "net"

    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
    pb "path/to/your/protobuf/package"
)

// server is used to implement your service.
type server struct {
    pb.UnimplementedYourServiceServer
}

// Serve gRPC with TLS
func main() {
    // Load the certificate and private key
    creds, err := credentials.NewServerTLSFromFile("server.crt", "server.key")
    if err != nil {
        log.Fatalf("Failed to generate credentials %v", err)
    }

    // Create a new gRPC server with TLS credentials
    s := grpc.NewServer(grpc.Creds(creds))
    pb.RegisterYourServiceServer(s, &server{})

    // Start listening on a port
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatalf("Failed to listen: %v", err)
    }
    log.Println("Serving gRPC on https://localhost:50051")
    
    // Serve gRPC server
    if err := s.Serve(lis); err != nil {
        log.Fatalf("Failed to serve: %v", err)
    }
}
    

gRPC Go TLS Transport Layer Security secure communication gRPC server gRPC client