Skip to content

Instantly share code, notes, and snippets.

@joekarl
Last active August 29, 2019 23:50
Show Gist options
  • Save joekarl/e38ffa0f5595c4c0b1ff to your computer and use it in GitHub Desktop.
Save joekarl/e38ffa0f5595c4c0b1ff to your computer and use it in GitHub Desktop.
Error handling go-libapns
package main
import (
apns "github.com"
"ioutils"
"net"
"time"
)
func main() {
apnsConnection, err := apns.NewAPNSConnection(&APNSConfig{
CertificateBytes: ioutil.ReadFile("path/to/cert.pem"),
KeyBytes: ioutil.Readfile("path/to/key.pem")
})
if err != nil {
//probably bad cert, or bad network
panic(err)
}
var payload *apns.Payload
var sendError *apns.ConnectionClose
for i := 0; i < 1000; i++ {
if sendError != nil {
break
}
payload = &apns.Payload {
Token: getTokenForUser(i),
AlertText: "This is a push notification",
}
select {
case apnsConnection.SendChannel <- payload:
//hooray! we wrote the payload to the socket
break
case sendError = <- apnsConnection.CloseChannel:
//something happened to our apns connection :(
//also it has disconnected itself from the socket
break
}
}
if sendError != nil {
//*list.List list of payloads that need to be resent
sendError.UnsentPayloads
//*apns.Payload payload which apple indicates caused error
// (only set if a payload caused the error)
sendError.ErrorPayload
//*apns.AppleError actual apple error information
sendError.Error
//bool if this is true, then we overflowed our buffer and
// some notifications were lost due to error
sendError.UnsentPayloadBufferOverflow
} else {
//everything was consumed by go-libapns
//unfortunately this doesn't mean everything was sent yet (due to internal framing)
//we must wait for either an error or for a short period to guarantee the network has flushed
select {
case <- time.After(1 * time.Second):
//should be good
apnsConnection.Disconnect()
break
case sendError = <- apnsConnection.CloseChannel:
//something happened to our apns connection :(
//also it has disconnected itself from the socket
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment