A Go context carries deadlines, cancellation signals, and key-value data across call boundaries. Generated gRPC service functions take a context.Context as their first parameter, so a caller can pass a time limit into a service call. section 6.1.1
Use a timeout when a slow dependency could make an upstream service miss its latency commitment. For an Order service waiting on Shipping or Payment, a bounded call can fail fast instead of waiting indefinitely. context.WithDeadline takes a target time; context.WithTimeout takes a duration. Both derive a context from a parent and return a cancellation function. section 6.1.1
Listing 6.1 Timeout pattern on the client side
shippingClient := shipping.NewShippingServiceClient(conn) #1
ctx, _ := context.WithDeadline(context.Background(),
time.Now().Add(1*time.Second)) #2
log.Println("Creating shipping...")
_, errCreate := shippingClient.Create(ctx,
&shipping.CreateShippingRequest{UserId: 23})
if errCreate != nil {
log.Printf("Failed to create shipping. Err: %v", errCreate)
} else {
log.Println("Shipping is created successfully.")
}
The Shipping client creates a one-second deadline and passes the resulting context to Create; the caller handles a returned error rather than assuming the shipment succeeded. section 6.1.1
Pass the same context into downstream calls to carry the caller’s time limit across service boundaries. A cancellation function can also stop work that is no longer needed: if several endpoints compete to provide a result, cancel the shared context once one returns. section 6.1.1
Context also connects a request to its logs. In a gRPC order operation, a logrus formatter can read span data from the log entry’s context and add trace_id and span_id fields to JSON output. Those fields let a logging backend find messages associated with the same operation. section 9.3.7
...
type serviceLogger struct {
formatter log.JSONFormatter #1
}
func (l serviceLogger) Format(entry *log.Entry) ([]byte, error) {
span := trace.SpanFromContext(entry.Context) #2
entry.Data["trace_id"] = span.SpanContext().TraceID().String()
entry.Data["span_id"] = span.SpanContext().SpanID().String()
//Below injection is Just to understand what Context has
entry.Data["Context"] = span.SpanContext()
return l.formatter.Format(entry) #3
}
...
The formatter retrieves the span from entry.Context and writes its trace and span IDs into the log entry before JSON formatting. section 9.3.7






