Getting Started with Interceptors
Learn how to create and use Goa interceptors
Goa interceptors provide a powerful, type-safe mechanism for injecting cross-cutting concerns into your service methods. They allow you to intercept and modify both requests and responses at both the client and server side, with full type safety and excellent IDE support.
Interceptors are components that allow you to add behavior that executes before, after, or around your service methods. They can:
Here’s a simple example of defining a client-side retry interceptor:
var RetryPolicy = Interceptor("RetryPolicy", func() {
Description("Implements exponential backoff retry for failed operations")
// Track retry attempts in result
WriteResult(func() {
Attribute("attempts")
})
})
var _ = Service("payment", func() {
// Apply retry policy to all service methods
ClientInterceptor(RetryPolicy)
Method("process", func() {
Payload(func() {
Attribute("amount", Int, "Payment amount")
Attribute("currency", String, "Payment currency")
})
Result(func() {
Attribute("id", String, "Transaction ID")
Attribute("status", String, "Transaction status")
Attribute("attempts", Int, "Number of retry attempts made")
})
// Method-specific configuration...
})
})
In this example, we define a RetryPolicy
interceptor that implements
exponential backoff for failed operations. Let’s break down the key components:
Interceptor Definition:
var RetryPolicy = Interceptor("RetryPolicy", func() {
This creates a new interceptor named “RetryPolicy”.
Result Modification:
WriteResult(func() {
Attribute("attempts")
})
The interceptor declares that it will write to an “attempts” field in the response, tracking how many retries were needed.
Service Application:
ClientInterceptor(RetryPolicy)
The interceptor is applied at the service level, meaning it will affect all methods in the service.
Method Definition:
The process
method shows how the interceptor integrates with the service:
attempts
field in the result allows the retry interceptor to report its activityWhen implemented, this interceptor will automatically retry failed operations with increasing delays between attempts, providing resilience against transient failures.
Interceptors are ideal for several common use cases in service architectures:
Note that for security concerns like authentication and authorization, you should use Goa’s built-in security DSL instead of interceptors, as it provides more robust and specialized security features.