6

I am trying to write a Go application that periodically polls a REST endpoint exposed by a PHP application. The Go polling application reads the payload into a struct and does further processing. I am looking for some recommendations for starting the implementation.

citizenBane
  • 337
  • 1
  • 4
  • 13
  • 1
    You may simply write a for loop which sleeps for sometime and poll the REST endpoint in every iteration. May be u will run the for loop in a dedicated goroutine. Else you may use Ticker (https://golang.org/pkg/time/#Ticker) also. – Nipun Talukdar Sep 07 '16 at 07:39
  • Thanks. Could this be implemented with long polling? – citizenBane Sep 07 '16 at 07:49
  • yes, can be used for long polling. – Nipun Talukdar Sep 07 '16 at 12:16
  • Sure it could be implemented with long polling if endpoint support this. You just don't Close connection but read chunks of data from http.Response.Body as them are available. – Uvelichitel Sep 07 '16 at 12:22

1 Answers1

12

Simplest way would be to use a Ticker:

ticker := time.NewTicker(time.Second * 1).C
go func() {
    for {
        select {
        case <- ticker:
            response,_ := http.Get("http://...")
            _, err := io.Copy(os.Stdout, response.Body)
            if err != nil {
                log.Fatal(err)
            }
            response.Body.Close()
        }
    }

}()


time.Sleep(time.Second * 10)
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40