Я пишу REST API в Go, следуя этому примеру как основа.
Теперь проблема, с которой я сталкиваюсь, заключается в том, что при выполнении нескольких одновременных запросов к маршруту GET он обслуживает первый результат для всех ожидающих клиентов. Вместо того, чтобы только отправлять ответ запрашивающему клиенту.
Я искал часы и пробовал все, что мог придумать. Это единственный найденный мной пост, похожий на мою проблему, но мою не решил. Это привело к неполному ответу json.
Дескриптор, который вызывается из маршрута GET:
func Index(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
//some variable declaration here
getResponses(w,...)
}
Метод getResponses:
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)
}
}
globalJsonObject
. Почему бы им всем не получить одинаковый ответ? - person JimB   schedule 06.12.2016