如何在http.ListenAndServe处理程序之外编写HTTP响应?

I'm setting up a HTTP server in Go, telling the server to handle all requests with the putRequestOnQueue function:

http.ListenAndServe(":6776", *handler)
http.HandleFunc("/", putRequestOnQueue)

The job of putRequestOnQueue is to put the response writer on a queue, to be pulled off and used to return a response at some future time.

func putRequestOnQueue(w http.ResponseWriter, r *http.Request){
    RequestQueue.Put(responseWriter)
}

However, it appears that once the ResponseWriter goes out of scope, the server returns a 200. I'd imagine it does this because it figures "oh, the function you told me was gonna handle this request just lost the writer, so I'm just gonna spit back a 200."

But I don't want this behavior. I want to be able to write back when I choose, from another function. Is there a way I can write back a response from another function without the server prematurely returning a 200?

Once the handler returns, the server sends a reply/status. You'll need something like:

func putRequestOnQueue(w http.ResponseWriter, r *http.Request){
    RequestQueue.Put(responseWriter)
    waitForResponse()
}

In other words, putRequestOnQueue shouldn't return until the response is ready. You can use a channel, for example, or whatever else to do this waiting.


Note, however, that this isn't very idiomatic Go. In Go we don't do as much async patterns as in other languages, because goroutines are cheap. Each HTTP handler is already called in a separate goroutine, so you might as well use your handler to do the work rather than dispatch the work to be done elsewhere.