Answer the question
In order to leave comments, you need to log in
How to do long polling on go?
I want to make a long polling method in my golang api. How to do it right?
Now implemented like this:
func longPollingHandler(w http.ResponseWriter, r *http.Request) {
done := make(chan struct{})
go checkUpdates(done)
select {
case <- done:
makeAnswer(w)
case <- time.After(20 * time.Second):
makeAnswer(w)
}
}
func checkUpdates(done chan<- struct{}) {
for i := 0; i < 20; i++ {
// Тут проверяю есть ли изменения в базе
// ...
if db.HasChanges() {
break;
}
time.Sleep(time.Second)
}
done <- struct{}{}
}
func makeAnswer(w http.ResponseWriter) {
// Тут шлю ответ клиенту
// ...
}
http.HandleFunc("/api/long_polling", longPollingHandler)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question