//在使用golang 作为服务器开发语言时,可能会遇到 要向iOS发送apns通知的情况
// 代码地址:
https://github.com/jeffasd/apns2
https://github.com/jeffasd/buford
示例:
注意go语言在传递参数时不能使用"' 使用""传递的参数是不对的
go run main.go -cert “../ck.p12” -token “7334073f95f5bd6b8f538f7895df1d6e384c63b4cff0fa0eba7477d6766fcbb1” -topic “com.zzcs.mengliao” - 这个是错误的
go run main.go -cert ck.p12 -token 7334073f95f5bd6b8f538f7895df1d6e384c63b4cff0fa0eba7477d6766fcbb1 -topic com.push.bundleid
./main -d e6d7330033380bb76bdd095c8ccb60e8e5de828d1a6d8f170e5b90b6036cd20f -c ck.p12 -p 123456 -e development
示例代码如下:
package main
import (
"flag"
"fmt"
"log"
"os"
"github.com/sideshow/apns2"
"github.com/sideshow/apns2/certificate"
)
func main() {
certPath := flag.String("cert", "", "Path to .p12 certificate file (Required)")
token := flag.String("token", "", "Push token (Required)")
topic := flag.String("topic", "", "Topic (Required)")
flag.Parse()
if *certPath == "" || *token == "" || *topic == "" {
flag.PrintDefaults()
os.Exit(1)
}
fmt.Printf("000-> %s\n", *certPath)
cert, err := certificate.FromP12File(*certPath, "123456")
if err != nil {
log.Fatal("Cert Error 111 :", err)
}
notification := &apns2.Notification{}
notification.DeviceToken = *token
notification.Topic = *topic
notification.Payload = []byte(`{
"aps" : {
"alert" : "Hello!"
}
}
`)
client := apns2.NewClient(cert).Development()
res, err := client.Push(notification)
if err != nil {
log.Fatal("Error:", err)
}
fmt.Printf("%v %v %v\n", res.StatusCode, res.ApnsID, res.Reason)
}
package main
import (
"log"
"fmt"
"github.com/sideshow/apns2"
"github.com/sideshow/apns2/certificate"
)
func main() {
cert, err := certificate.FromP12File("ck.p12", "123456")
if err != nil {
log.Fatal("Cert Error:", err)
}
notification := &apns2.Notification{}
notification.DeviceToken = "7334073f95f5bd6b8f538f7895df1d6e384c63b4cff0fa0eba7477d6766fcbb1"
notification.Topic = "com.push.bundleid"
notification.Payload = []byte(`{"aps":{"alert":"Hello!"}}`) // See Payload section below
client := apns2.NewClient(cert).Development()
res, err := client.Push(notification)
if err != nil {
log.Fatal("Error:", err)
}
fmt.Printf("%v %v %v\n", res.StatusCode, res.ApnsID, res.Reason)
}
package main
import (
"flag"
"fmt"
"log"
"os"
"io/ioutil"
)
/*
获取程序运行路径
*/
func getCurrentDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
beego.Debug(err)
}
return strings.Replace(dir, "\\", "/", -1)
}
func main() {
//p12bytes, err := ioutil.ReadFile("../../text.txt");
getCurrentDirectory();
p12bytes, err := ioutil.ReadFile("../../certificate/text.txt");
fmt.Printf("read mian \n");
fmt.Printf("FromP12File -> %s\n", p12bytes)
if err != nil {
log.Fatal("Error:", err)
}else{
fmt.Printf("read Success");
}
}