I
I
ilitaexperta2018-05-02 03:28:44
go
ilitaexperta, 2018-05-02 03:28:44

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)

Everything works, but there was a feeling that the responses to other api methods (not long polling) began to arrive with a delay. I suspect that this is due to a slip in the goroutine.
How to do it right in the end? Please don't suggest adding 10 frameworks, libraries and dependencies.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question