Code walkthrough: Gitea middlewares

This is one of the Code walkthrough I wrote while exploring the Gitea codebase.

The Gitea server is based on chi. The chi middlewares are functions that perform an action either before the request reaches the handler or after the response is returned by the handler. Gitea defines its own set of middleware that are installed on most routes (with the chi’s Use method improved to accept multiple arguments).

  1. Wraps the http.ResponseWriter in Gitea’s own ResponseWriter which can have a set of of functions to “… be called before the ResponseWriter has been written to. This is useful for setting headers or any other operations that must happen before a response has been written.”
  2. Install trusted reverse proxies depending on the Gitea REVERSE_PROXY_TRUSTED_PROXIES setting and based on chi’s proxy middleware.
  3. Install chi’s stripslashes middleware.
  4. Install a router logger depending on the Gitea ROUTER_LOG_LEVEL setting.
  5. Install an access logger depending on the Gitea ENABLE_ACCESS_LOG setting.
  6. Install a safeguard to gracefully recover from nested failures.

Some middlewares installed on the /api/v1 routes perform similar functions but have a different signature. When given a middleware with the func(ctx *context.APIContext) type, the Use method will wrap it as a chi middleware. For instance the ToggleAPI middleware from the context module is installed when initializing the routes for the api. The req *http.Request argument expected in a chi/http middleware can still be accessed via the ctx.Req member of the ctx *context.APIContext argument.

Gitea improves the chi route Group method with an optional middleware last argument. For instance the sudo middleware is set on all API routes because it is the last argument of the Group enclosing all of them.

1 Like