【Go言語】Appleプッシュ通知を使う【APN】
ゴール
- 先日【iOS】Push通知の実装(サーバ編その1)【できた】 - DRYな備忘録においてRubyで実装した
- 今回はこれをGo言語でやる
記録
こういうのがある
- anachronistic/apns · GitHub
- 上記ブログで使用したRuby製のhoustonとの違いは
- クライアントを初期化するときにpemファイルを2つ渡しているところか
houstonと読み比べをして
- houstonで使用したpemファイルは以下のようなフォーマットになっている
Bag Attributes friendlyName: Apple Development IOS Push Services: = my.app.bundle.id localKeyID: hex hex hex hex subject=/UID=com.otiai10.app.ApnSample/CN=Apple Development IOS Push Services: my.app.bundle.id/OU=DEVCODE/C=JP issuer=/C=US/O=Apple Inc./OU=Apple Worldwide Developer Relations/CN=Apple Worldwide Developer Relations Certification Authority -----BEGIN CERTIFICATE----- Base64Encodedな文字列 Base64Encodedな文字列 Base64Encodedな文字列 -----END CERTIFICATE----- Bag Attributes friendlyName: name localKeyID: hex hex hex hex Key Attributes: <No Attributes> -----BEGIN RSA PRIVATE KEY----- Base64Encodedな文字列 Base64Encodedな文字列 Base64Encodedな文字列 -----END RSA PRIVATE KEY-----
- これを単純に2つのファイルに分けた
cert.pem
Bag Attributes friendlyName: Apple Development IOS Push Services: = my.app.bundle.id localKeyID: hex hex hex hex subject=/UID=com.otiai10.app.ApnSample/CN=Apple Development IOS Push Services: my.app.bundle.id/OU=DEVCODE/C=JP issuer=/C=US/O=Apple Inc./OU=Apple Worldwide Developer Relations/CN=Apple Worldwide Developer Relations Certification Authority -----BEGIN CERTIFICATE----- Base64Encodedな文字列 Base64Encodedな文字列 Base64Encodedな文字列 -----END CERTIFICATE-----
key.pem
Bag Attributes friendlyName: name localKeyID: hex hex hex hex Key Attributes: <No Attributes> -----BEGIN RSA PRIVATE KEY----- Base64Encodedな文字列 Base64Encodedな文字列 Base64Encodedな文字列 -----END RSA PRIVATE KEY-----
anachronistic/apnsを使うGoを書く
package main import ( "fmt" apns "github.com/anachronistic/apns" ) func main() { payload := apns.NewPayload() payload.Alert = "Hello, world!" payload.Badge = 42 payload.Sound = "bingbong.aiff" pn := apns.NewPushNotification() pn.DeviceToken = "xxxxxxxxxxxxxxxxxxx" // houstonでは"<xxxxxxx xxxxxxx xxxxxxx>"という文字列だったが // ここでは"<>"とスペースを取り除いたものを使う pn.AddPayload(payload) client := apns.NewClient("gateway.sandbox.push.apple.com:2195", "cert.pem","key.pem") resp := client.Send(pn) alert, _ := pn.PayloadString() fmt.Println("Alert\t", alert) fmt.Println("Succe\t", resp.Success) fmt.Println("Error\t", resp.Error) }
これを実行
stdout
Alert {"aps":{"alert":"Hello, world!","badge":42,"sound":"bingbong.aiff"}} Succe true Error <nil>
いけた
雑感
- pemファイルふたつにすんのが普通なのかな
- まあいっか、動いたし
DRY