'Golang middleware chain: How can the logger middleware access downstream context information?

I'm trying to build a Golang http middleware chain to achieve the following:

  • Request logger middleware (with or without authentication information e.g. tenant-id) -> log for every authenticated and unauthenticated request
  • Authentication middleware
  • Authorization middleware
  • Handlers using the user info

All middleware parts pass their information using the context.WithValue function.

The problem I'm currently facing is that the request logger middleware cannot access the user information (to log a tenant id).

I tried using the request.WithContext and request.Context methods, but request.WithContext doesn't change the request in the logger middleware.

How can the logger middleware access downstream context information?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source