gRPC-Gateway generates a reverse proxy that translates RESTful HTTP/JSON requests into gRPC calls, allowing you to serve both protocols from a single Go backend. You define your API in a .proto file with google.api.http annotations, generate the Go code and gateway handlers using protoc and buf, then wire them into your main.go to serve both gRPC and REST on the same port.
protoc --go_out=. --go-grpc_out=. --grpc-gateway_out=. \
--grpc-gateway_opt logtostderr=true \
--grpc-gateway_opt paths=source_relative \
api/*.proto
# In main.go
import (
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
)
func main() {
mux := runtime.NewServeMux()
// Register generated handlers
_ = pb.RegisterMyServiceHandlerFromEndpoint(ctx, mux, "localhost:9090", nil)
// Serve both gRPC and REST on same port
lis, _ := net.Listen("tcp", ":8080")
grpcSrv := grpc.NewServer()
pb.RegisterMyServiceServer(grpcSrv, &server{})
go grpcSrv.Serve(lis)
httpSrv := &http.Server{Handler: mux}
httpSrv.Serve(lis)
}