I'm trying to create a map that stores http.ResponseWriters so that I can write to them later, after a separate thread has done the relevant computation. The map is defined in my main as follow:jobs := make(map[uint32]http.ResponseWriter)
I then pass this map to a handle function like so:
r.HandleFunc("/api/{type}/{arg1}", func(w http.ResponseWriter, r *http.Request) {
typ, _ := strconv.Atoi(mux.Vars(r)["type"])
AddReqQueue(w, ReqQueue, typ, mux.Vars(r)["arg1"], jobs, ids)
}).Methods("get")
After that I process the reuqeuest and add it to a channel:
func AddReqQueue(w http.ResponseWriter, ReqQueue chan mssg.WorkReq, typ int, arg1 string, jobs map[uint32]http.ResponseWriter, ids []uint32) {
var id uint32
id, ids = ids[0], ids[1:] // get a free work id
jobs[id] = w
fmt.Println("Adding req to queue")
ReqQueue <- mssg.WorkReq{Type: uint8(typ), Arg1: arg1, WId: id}
}
Inside this function I have tested and am able to write data to the ReponseWriter, however later when I try to use the map in:
func SendResp(RespQueue chan mssg.WorkResp, jobs map[uint32]http.ResponseWriter) {
for {
resp := <-RespQueue
jobs[resp.WId].Header().Set("Content-Type", "text/plain")
_, err := jobs[resp.WId].Write(resp.Data) // ERROR IS COMING FROM HERE
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
}
}
}
It doesn't work. No matter what I pre-set the header too or try to write (even just a simple string I hardcoded) I get a err of
Conn.Write wrote more than the declared Content-Length
I know I'm accessing the right struct in the map, it just seems as if the ReponseWriter
has gone out of context or been corrupted, also i know that the headers shouldn't really matter since it is the first time I am calling Write()
and therefore it should create the headers for me.
@elithrar was correct. I wasn't aware that the http.ResponseWriter object became invalid after the handler exited. If I just force my handler to wait, it works fine.