I'm writing an REST API in Go following this example as a basis.
Now the issue i'm having is while doing multiple simultaneous requests to the GET route, it serves the first result to all pending clients. Instead of only sending the response to the requesting client.
I've been searching for hours and trying everything i could think of. This is the only post i found that looked like my issue, but didn't solve mine. It resulted in a incomplete json response..
The handle that's being called from the GET route:
func Index(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
//some variable declaration here
getResponses(w,...)
}
The getResponses method:
func getResponses(w http.ResponseWriter, ...) {
responses := 0
totalRequests = 0
var completeChannel = make(chan string, 1)
start = time.Now()
go func() {
totalRequests += 1
//some method()
responses += 1
fmt.Println("method done")
routineDone(responses, completeChannel)
}()
go func() {
totalRequests += 1
//some method()
responses += 1
fmt.Println("method done")
routineDone(responses, completeChannel)
}()
select {
case r := <-completeChannel:
fmt.Println(r)
sendResponse(w)
case <-time.After(time.Second * 10):
sendResponse(w)
}
}
func routineDone(responses int, completeChannel chan string) {
if totalRequests > 0 {
fmt.Printf("completed %d of %s requests. duration: %s \n", responses, strconv.Itoa(totalRequests), time.Since(start))
}
if responses == totalRequests && totalRequests != 0 {
completeChannel <- "DONE"
}
}
func sendResponse(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(globalJsonObject); err != nil {
panic(err)
}
}