Skip to content

Instantly share code, notes, and snippets.

@ik5
Created January 21, 2017 15:26
Show Gist options
  • Save ik5/ad9783afd50e0b769f2386e8faaea427 to your computer and use it in GitHub Desktop.
Save ik5/ad9783afd50e0b769f2386e8faaea427 to your computer and use it in GitHub Desktop.
Listen to a Pg event in go
package main
import (
"database/sql"
"fmt"
"time"
"github.com/lib/pq"
)
func waitForNotification(l *pq.Listener) {
for {
select {
case ch := <-l.Notify:
fmt.Printf("received notification, new cdr available %#v\n", ch)
return
case <-time.After(90 * time.Second):
go func() {
l.Ping()
}()
// Check if there's more work available, just in case it takes
// a while for the Listener to notice connection loss and
// reconnect.
// fmt.Println("received no work for 90 seconds, checking for new work")
return
}
}
}
func reportProblem(ev pq.ListenerEventType, err error) {
fmt.Printf("%+v, err: %s", ev, err)
}
func main() {
conninfo := "host=localhost user=postgres dbname=tts sslmode=disable"
db, err := sql.Open("postgres", conninfo)
if err != nil {
panic(err)
}
fmt.Println(db, conninfo)
reportProblem := func(ev pq.ListenerEventType, err error) {
if err != nil {
fmt.Println(err.Error())
}
}
listener := pq.NewListener(conninfo, 10*time.Second, time.Minute, reportProblem)
err = listener.Listen("cdr_created")
if err != nil {
panic(err)
}
fmt.Println("entering main loop")
for {
// process all available work before waiting for notifications
//getWork(db)
waitForNotification(listener)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment