Gateway Setup
The gateway runs as a separate process that proxies HTTP/JSON requests to your gRPC server.
cmd/gateway/main.go
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"shortener/pb"
)
func main() {
ctx := context.Background()
mux := runtime.NewServeMux()
err := pb.RegisterLinkServiceHandlerFromEndpoint(ctx, mux, "localhost:50051",
[]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())},
)
if err != nil {
log.Fatal(err)
}
fmt.Println("HTTP gateway on :8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}Running
Start the gRPC server first, then the gateway in a second terminal:
# Terminal 1
go run .
# Terminal 2
go run ./cmd/gateway/Test with curl
curl -X POST http://localhost:8080/v1/links -d '{"url":"https://golang.org"}'
curl http://localhost:8080/v1/links/abc123