Batch Create
Client streaming example: send multiple URLs in a stream, get one summary response back.
Server — main.go
Add "io" to your imports, then add this method:
func (s *linkServer) BatchCreateLinks(stream pb.LinkService_BatchCreateLinksServer) error {
var created []*pb.Link
for {
req, err := stream.Recv()
if err == io.EOF {
// Client is done — send the summary and close
return stream.SendAndClose(&pb.BatchCreateLinksResponse{
CreatedCount: int64(len(created)),
Links: created,
})
}
if err != nil {
return err
}
id := s.nextID.Add(1)
link := &pb.Link{
Id: id,
Url: req.GetUrl(),
ShortCode: shortCode(),
}
s.mu.Lock()
s.links[link.ShortCode] = link
s.mu.Unlock()
created = append(created, link)
}
}Client — cmd/client/main.go
package main
import (
"context"
"fmt"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"shortener/pb"
)
func main() {
conn, err := grpc.NewClient("localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
client := pb.NewLinkServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Open the stream
stream, err := client.BatchCreateLinks(ctx)
if err != nil {
log.Fatal(err)
}
// Send URLs one by one
urls := []string{
"https://example.com/article-one",
"https://example.com/article-two",
"https://example.com/article-three",
}
for _, url := range urls {
if err := stream.Send(&pb.CreateLinkRequest{Url: url}); err != nil {
log.Fatal(err)
}
fmt.Printf("sent: %s\n", url)
}
// Close sending side and get the response
resp, err := stream.CloseAndRecv()
if err != nil {
log.Fatal(err)
}
fmt.Printf("\ncreated %d links:\n", resp.GetCreatedCount())
for _, link := range resp.GetLinks() {
fmt.Printf(" %s -> %s\n", link.GetShortCode(), link.GetUrl())
}
}Expected Output
sent: https://example.com/article-one
sent: https://example.com/article-two
sent: https://example.com/article-three
created 3 links:
k7m2px -> https://example.com/article-one
a3f9wq -> https://example.com/article-two
zt04bn -> https://example.com/article-three💡 The client sends all URLs before getting any response. The server processes them as they arrive and responds once at the end — that's the client streaming pattern.