0

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)
    }
}
Community
  • 1
  • 1
JoeriV
  • 357
  • 2
  • 9
  • You're sending all clients the same `globalJsonObject`. Why wouldn't they all receive the same response? – JimB Dec 06 '16 at 18:57
  • Good point. But let's say i would pass this object into the method somehow. How can i distinct between the response writers, so it correspondents to the correct requesting client? – JoeriV Dec 06 '16 at 19:01
  • 1
    I don't understand. You don't need to distinguish between anything, because there's only 1 ResponseWriter in the call to getResponses. The RepsonseWriter should always be paired with its request. – JimB Dec 06 '16 at 19:06
  • You were completely right! The global variable was just overriding the previous requests values! Thanks a lot! – JoeriV Dec 06 '16 at 20:10

0 Answers0