Server Hooks can be attached to a generated server constructor to provide callbacks for specific points in the request lifecycle. They are ideal for observability tasks like logging requests, recording response times, or reporting metrics.
Key behaviors:
- Every hook receives the request
context.Context and can return a modified context.Context. - The
Error hook is only triggered if the handler returns an error. - Use
twirp.WithServerHooks when instantiating your server.
Common hook callbacks include RequestRouted, Error, and ResponseSent.
// NewLoggingServerHooks logs request and errors to stdout in the service
func NewLoggingServerHooks() *twirp.ServerHooks {
return &twirp.ServerHooks{
RequestRouted: func(ctx context.Context) (context.Context, error) {
method, _ := twirp.MethodName(ctx)
log.Println("Method: " + method)
return ctx, nil
},
Error: func(ctx context.Context, twerr twirp.Error) context.Context {
log.Println("Error: " + string(twerr.Code()))
return ctx
},
ResponseSent: func(ctx context.Context) {
log.Println("Response Sent (error or success)")
},
}
}
// Usage during server instantiation:
server := NewHaberdasherServer(svcImpl,
twirp.WithServerHooks(NewLoggingServerHooks()))