Home > Backend Development > Golang > How can I pass and access context information in Go HTTP Handlers and Middleware?

How can I pass and access context information in Go HTTP Handlers and Middleware?

Susan Sarandon
Release: 2024-11-16 04:17:03
Original
820 people have browsed it

How can I pass and access context information in Go HTTP Handlers and Middleware?

Passing Context in Middleware and HandlerFunc

In Go, the context package provides functionality for passing information between request handlers. This is particularly useful for middleware, which can perform actions before and after the execution of a handler function.

Creating and Passing Context

In the context of middleware, we can create a new context by calling context.WithValue on the request's context, providing a key and value pair. This new context should then be used when calling the handler's ServeHTTP method.

For instance, in the provided code snippet, the checkAuth middleware function receives the request context and auth token as input. It returns a wrapped handler function that checks the auth token.

func checkAuth(authToken string) util.Middleware {
    return func(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if r.Header.Get("Auth") != authToken {
                util.SendError(w, "...", http.StatusForbidden, false)
                return
            }
            h.ServeHTTP(w, r)
        })
    }
}
Copy after login

To initialize the context with the auth token, we can call context.WithValue on the request's context, as shown below:

func main() {
    authToken, ok := getAuthToken()
    if !ok {
        panic("...")
    }
    ctx := context.WithValue(r.Context(), "auth_token", authToken)
    router.Handle("/hello", util.UseMiddleware(authCheck, Handler, ...))
}
Copy after login

This new context will then be used when the middleware handler calls the original handler's ServeHTTP method.

Accessing Context in Handlers

The handler can access the context information by calling r.Context(), which returns the current context. The value can be retrieved using the Value method, as shown in the code snippet below:

func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    authToken := r.Context().Value("auth_token").(string)
    // ...
}
Copy after login

The above is the detailed content of How can I pass and access context information in Go HTTP Handlers and Middleware?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template