DRYな備忘録

Don't Repeat Yourself.

【Go言語】Appleプッシュ通知を使う【APN】

ゴール

記録

こういうのがある

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>

iPhone

f:id:otiai10:20140810173542j:plain

いけた

雑感

  • pemファイルふたつにすんのが普通なのかな
  • まあいっか、動いたし

DRY