// Creating a new context ctx := middleware.NewContext() // Setting a value in the context ctx.SetValue("user", currentUser) // Getting a value from the context user := ctx.Value("user").(User)
// Middleware function func AuthMiddleware(inner http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Retrieve user from context user := r.Context().Value("user").(User) if user.IsAuthenticated() { // Call the next middleware/handler in chain inner.ServeHTTP(w, r) } else { // Return a 401 Unauthorized response w.WriteHeader(http.StatusUnauthorized) } }) }In this example, we define a middleware function `AuthMiddleware` that checks if the user is authenticated before allowing access to the next middleware or handler in the chain. We retrieve the user from the request's context using `r.Context().Value()`. If the user is authenticated, we call the next middleware/handler using `inner.ServeHTTP()`. Otherwise, we return a 401 Unauthorized response. Overall, the `github.com/go-gitea/gitea/modules/middleware` package provides useful middleware utilities in Go for handling web requests and responses.