如何从Handler类型获取响应头?

Given a middleware function with a signature like:

func Middleware(handler http.Handler) http.Handler

How can I get response headers set and passed to it from a calling function?

First a HandlerFunc (the "base" or main server function) is initialized with some response headers. Then it is passed to and wrapped by the middleware function in the conventional manner.

How can I get the Response and its headers from the handler parameter?

I've tried a number of things but can't get at the header values.

Strictly speaking, you cannot. In priniple, the http.Handler is a function that is invoked for each request. As such, it is not bound to any specific request; it will be re-used for an arbitrary number of requests. As such, there is no way to retrieve HTTP request or response headers from an existing http.Handler object.

You can however, decorate the handler with your own middleware to access HTTP response headers that were set by the middleware function.

A middleware function as described in your question will typically be implemented like this:

func Middleware(originalHandler http.Handler) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        // call the original handler that is wrapped by this middleware
        originalHandler.ServeHTTP(rw, req)
    }
}

This function "decorates" the original http.Handler that is passed as a parameter into the middleware function by returning a new handler that implements custom logic and calls the original (wrapped) handler function at some point.

Within the new function, you can access the http.ResponseWriter object as usual to access the HTTP headers that were already set by the decorated handlers:

func Middleware(originalHandler http.Handler) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        // Add new headers to the response...
        rw.Header().Set("X-My-Own-Header", "foo")

        // ...or access data from the original request
        fmt.Println(req.Header().Get("X-My-Request-Header")

        // call the original handler that is wrapped by this middleware
        originalHandler.ServeHTTP(rw, req)

        // Access headers in the response object
        rw.Header().Get("X-Header-Set-By-Middleware")
    }
}