Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodically polling a REST endpoint in Go

Tags:

rest

go

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.

like image 712
citizenBane Avatar asked Sep 07 '16 07:09

citizenBane


People also ask

What is polling an endpoint?

Polling is the process of repeatedly hitting the same endpoint looking for new data. We don't like doing this (its wasteful), vendors don't like us doing it (again, its wasteful) and users dislike it (they have to wait a maximum interval to trigger on new data).

What are two advantages Webhooks have over polling?

Polling requests are made by a client, while webhook requests are made by a server. Webhooks are also automatically triggered when an event occurs, whereas polling is set up to run at fixed intervals and runs whether there is a new event or not.

What is constant polling?

Constant polling of an endpoint is wasteful in terms of resources committed to the action from the developer, in terms of the traffic seen by the vendors, and in terms of actual result to effort.

What are API polls?

The Polling API is used to retrieve the reporting data from a request. The Polling API endpoint will respond to successful requests with compressed gzip. The response must be uncompressed to retrieve the data.


1 Answers

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)
like image 89
Alexey Soshin Avatar answered Sep 29 '22 05:09

Alexey Soshin