From 86654170c0ad8101bcdbece64a9ccd377ab04686 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Sat, 26 Mar 2016 23:42:22 +0800 Subject: [PATCH] Add global ios client. Signed-off-by: Bo-Yi Wu --- global.go | 2 ++ main.go | 18 ++++++++++++++---- notification.go | 19 ++++--------------- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/global.go b/global.go index 1485824..cc5e6ce 100644 --- a/global.go +++ b/global.go @@ -2,9 +2,11 @@ package main import ( "crypto/tls" + apns "github.com/sideshow/apns2" ) var ( PushConf ConfYaml CertificatePemIos tls.Certificate + ApnsClient *apns.Client ) diff --git a/main.go b/main.go index 4f60504..5c10739 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "github.com/gin-gonic/gin" "log" "net/http" + apns "github.com/sideshow/apns2" "github.com/sideshow/apns2/certificate" ) @@ -70,13 +71,22 @@ func main() { return } - CertificatePemIos, err = certificate.FromPemFile(PushConf.Ios.PemKeyPath, "") + if PushConf.Ios.Enabled { + CertificatePemIos, err = certificate.FromPemFile(PushConf.Ios.PemKeyPath, "") - if err != nil { - log.Println("Cert Error:", err) + if err != nil { + log.Println("Cert Error:", err) - return + return + } + + if PushConf.Ios.Production { + ApnsClient = apns.NewClient(CertificatePemIos).Production() + } else { + ApnsClient = apns.NewClient(CertificatePemIos).Development() + } } + endless.ListenAndServe(":"+PushConf.Core.Port, GetMainEngine()) } diff --git a/notification.go b/notification.go index 0cf8b88..f25361a 100644 --- a/notification.go +++ b/notification.go @@ -61,21 +61,11 @@ type RequestPushNotification struct { func pushNotification(notification RequestPushNotification) bool { var ( success bool - apnsClient *apns.Client ) - if PushConf.Ios.Production { - apnsClient = apns.NewClient(CertificatePemIos).Production() - } else { - apnsClient = apns.NewClient(CertificatePemIos).Development() - } - switch notification.Platform { case PlatFormIos: - success = pushNotificationIos(notification, apnsClient) - if !success { - apnsClient = nil - } + success = pushNotificationIos(notification) case PlatFormAndroid: success = pushNotificationAndroid(notification) } @@ -83,7 +73,7 @@ func pushNotification(notification RequestPushNotification) bool { return success } -func pushNotificationIos(req RequestPushNotification, client *apns.Client) bool { +func pushNotificationIos(req RequestPushNotification) bool { for _, token := range req.Tokens { notification := &apns.Notification{} @@ -168,7 +158,7 @@ func pushNotificationIos(req RequestPushNotification, client *apns.Client) bool notification.Payload = payload // send ios notification - res, err := client.Push(notification) + res, err := ApnsClient.Push(notification) if err != nil { log.Println("There was an error", err) @@ -177,11 +167,10 @@ func pushNotificationIos(req RequestPushNotification, client *apns.Client) bool if res.Sent() { log.Println("APNs ID:", res.ApnsID) + return true } } - client = nil - return true }