• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang gcm.NewMessage函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/alexjlockwood/gcm.NewMessage函数的典型用法代码示例。如果您正苦于以下问题:Golang NewMessage函数的具体用法?Golang NewMessage怎么用?Golang NewMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewMessage函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: CreateCard

func CreateCard(notif me.NotifModel, ts int) string {
	db.CardCounter += 1
	cardId := strconv.Itoa(db.CardCounter)
	db.Card[cardId] = me.CardModel{cardId, notif.Id, ts, false}
	if owner, ok := db.User[notif.OwnerId]; ok {
		if client, okk := db.User[notif.ClientId]; okk {
			owner.CardIds = append(owner.CardIds, cardId)
			db.User[notif.OwnerId] = owner

			data := map[string]interface{}{"title": notif.Name, "id": cardId}
			regIDs := []string{client.RegId}
			msg := gcm.NewMessage(data, regIDs...)

			// Create a Sender to send the message.
			sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}

			// Send the message and receive the response after at most two retries.
			_, err := sender.Send(msg, 2)
			if err != nil {
				fmt.Println("Failed to send message: %v", err)
			} else {
				fmt.Println("Message is sent.")
			}

			return cardId
		}
	}
	return ""
}
开发者ID:btasdoven,项目名称:Notifier,代码行数:29,代码来源:server.go


示例2: sendAndroidNotification

func sendAndroidNotification(msg *PushNotification) {
	var data map[string]interface{}
	if msg.Type == PUSH_TYPE_CLEAR {
		data = map[string]interface{}{"type": PUSH_TYPE_CLEAR, "channel_id": msg.ChannelId, "team_id": msg.TeamId}
	} else {
		data = map[string]interface{}{"type": PUSH_TYPE_MESSAGE, "message": emoji.Sprint(msg.Message), "channel_id": msg.ChannelId, "channel_name": msg.ChannelName, "team_id": msg.TeamId}
	}

	regIDs := []string{msg.DeviceId}
	gcmMsg := gcm.NewMessage(data, regIDs...)

	sender := &gcm.Sender{ApiKey: CfgPP.AndroidApiKey}

	if len(CfgPP.AndroidApiKey) > 0 {
		LogInfo("Sending android push notification")
		resp, err := sender.Send(gcmMsg, 2)

		if err != nil {
			LogError(fmt.Sprintf("Failed to send GCM push sid=%v did=%v err=%v", msg.ServerId, msg.DeviceId, err))
			return
		}

		if resp.Failure > 0 {
			LogError(fmt.Sprintf("Android response failure: %v", resp))
		}
	}
}
开发者ID:mattermost,项目名称:push-proxy,代码行数:27,代码来源:server.go


示例3: sendMessageToGCM

func (gcmConnector *GCMConnector) sendMessageToGCM(msg server.MsgAndRoute) {
	gcmId := msg.Route.ApplicationId

	payload := gcmConnector.parseMessageToMap(msg.Message)

	var messageToGcm = gcm.NewMessage(payload, gcmId)
	guble.Info("sending message to %v ...", gcmId)
	result, err := gcmConnector.sender.Send(messageToGcm, 5)
	if err != nil {
		guble.Err("error sending message to cgmid=%v: %v", gcmId, err.Error())
		return
	}

	errorJson := result.Results[0].Error
	if errorJson != "" {
		gcmConnector.handleJsonError(errorJson, gcmId, msg.Route)
	} else {
		guble.Debug("delivered message to gcm cgmid=%v: %v", gcmId, errorJson)
	}

	//we only send to one receiver, so we know that we can replace the old id with the first registration id (=canonical id)
	if result.CanonicalIDs != 0 {
		gcmConnector.replaceSubscriptionWithCanonicalID(msg.Route, result.Results[0].RegistrationID)
	}
}
开发者ID:tkrille,项目名称:guble,代码行数:25,代码来源:gcm_connector.go


示例4: Done

/* Mark the card as completed and
   Send a notification to the owner of the card
*/
func Done(c *gin.Context) {
	cardId := c.Param("card_id")

	if card, ok := db.Card[cardId]; ok {
		card.Completed = true
		db.Card[cardId] = card
		if notif, okk := db.Notif[card.NotifId]; okk {
			if user, okkk := db.User[notif.OwnerId]; okkk {
				data := map[string]interface{}{"title": notif.Name + " is done.", "id": cardId}
				regIDs := []string{user.RegId}
				msg := gcm.NewMessage(data, regIDs...)

				// Create a Sender to send the message.
				sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}

				// Send the message and receive the response after at most two retries.
				_, err := sender.Send(msg, 2)
				if err != nil {
					c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to send message: %v", err))
				} else {
					c.String(http.StatusOK, "Message is sent.")
				}
			}
		}
	} else {
		c.String(http.StatusNotFound, "")
	}
}
开发者ID:btasdoven,项目名称:Notifier,代码行数:31,代码来源:server.go


示例5: broadcastMessage

func (gcmConnector *GCMConnector) broadcastMessage(msg server.MsgAndRoute) {
	topic := msg.Message.Path
	payload := gcmConnector.parseMessageToMap(msg.Message)
	guble.Info("broadcasting message with topic %v ...", string(topic))

	subscriptions := gcmConnector.kvStore.Iterate(GCM_REGISTRATIONS_SCHEMA, "")
	count := 0
	for {
		select {
		case entry, ok := <-subscriptions:
			if !ok {
				guble.Info("send message to %v receivers", count)
				return
			}
			gcmId := entry[0]
			//TODO collect 1000 gcmIds and send them in one request!
			broadcastMessage := gcm.NewMessage(payload, gcmId)
			go func() {
				//TODO error handling of response!
				_, err := gcmConnector.sender.Send(broadcastMessage, 3)
				guble.Debug("sent broadcast message to gcmId=%v", gcmId)
				if err != nil {
					guble.Err("error sending broadcast message to cgmid=%v: %v", gcmId, err.Error())
				}
			}()
			count++
		}
	}
}
开发者ID:tkrille,项目名称:guble,代码行数:29,代码来源:gcm_connector.go


示例6: notify

func notify(meeting Meeting, status int) {

	data := map[string]interface{}{
		"action":       "meeting_started",
		"meeting_id":   meeting.Id.Hex(),
		"meeting_goal": meeting.Goal,
	}

	devices := devices(meeting)
	msg := gcm.NewMessage(data, devices...)

	cfg := config.Section("gcm")

	apikey := cfg.Key("apikey").String()

	sender := &gcm.Sender{ApiKey: apikey}

	_, err := sender.Send(msg, cfg.Key("retries").MustInt(3))

	if err != nil {
		log.Fatal("Failed to send message:", err)
	} else {
		log.Print(len(devices), " devices notified that ", meeting.String(), " changed to ", status)
	}
}
开发者ID:albulescu,项目名称:meetings-daemon,代码行数:25,代码来源:main.go


示例7: NotifyUsers

func NotifyUsers(deviceTokens []string) error {
	sender := &gcm.Sender{ApiKey: "AIzaSyBEHLA1FR4OlCRQE1vPv_mfqQaIF0ICZeA"}
	message := gcm.NewMessage(nil, deviceTokens...)
	_, err := sender.Send(message, 2)
	fmt.Println("Successfully sent a notification to device token : ", deviceTokens)
	if err != nil {
		return fmt.Errorf("Error sending notifications: %s", err)
	}
	return nil
}
开发者ID:arissetyawan,项目名称:ToDoLite-Notifications,代码行数:10,代码来源:handler.go


示例8: Send

func (n *Notification) Send() (errList Notification, err error) {
	// GCM
	apnTask := make(chan bool)
	gcmTask := make(chan bool)
	var (
		apnWG sync.WaitGroup
		gcmWG sync.WaitGroup
	)
	go func() { // parallel between APN and GCM
		// APN
		p := apns.NewPayload()
		p.APS.Alert.Body = n.Message
		p.APS.ContentAvailable = 1
		m := apns.NewNotification()
		m.Payload = p
		m.Priority = apns.PriorityImmediate
		apnWG.Add(len(n.APNReceivers))
		for _, v := range APNReceivers {
			go func() {
				m.DeviceToken = v
				apnClient.Send(m)
				apnWG.Done()
			}() // parallel for APN
		}
		// HERE err handling for APN
		go func() {
			for _, f := range apnClient.FailedNotifs {
				errList.APNReceivers = append(errList.APNReceivers, f.Notif.ID)
			}
		}()
		apnWG.Wait()
		apnTask <- true
	}()
	// GCM
	go func() {
		gcmWG.Add(len(n.GCMReceivers))
		data := map[string]interface{}{"message": n.Message}
		for _, v := range GCMReceivers() {
			go func() {
				d := gcm.NewMessage(data, v)
				_, err := gcmClient.Send(d, 0)
				if err != nil {
					errList.GCMReceivers = append(errList.GCMReceivers, v)
				}
				gcmWG.Done()
			}()
		}
		gcmWG.Wait()
		gcmTask <- true
	}()
	<-apnTask
	<-gcmTask
	return
}
开发者ID:Qs-F,项目名称:gotification,代码行数:54,代码来源:gotification.go


示例9: Send

// Send Push
func (self *Gcm) Send() (interface{}, error) {
	msg := gcm.NewMessage(self.Data, self.RegIds...)
	// Create a Sender to send the message.
	sender := &gcm.Sender{ApiKey: APIKEY}
	// Send the message and receive the response after at most two retries.
	response, err := sender.Send(msg, 2)
	if err != nil {
		return response, err
	}
	return response, nil
}
开发者ID:worg,项目名称:go,代码行数:12,代码来源:gcm.go


示例10: Check

// Check returns nil if health-check succeeds, or an error if health-check fails
// by sending a request with only apikey. If the response is processed by the GCM endpoint
// the gcmStatus will be UP, otherwise the error from sending the message will be returned.
func (conn *GCMConnector) Check() error {
	payload := conn.parseMessageToMap(&protocol.Message{Body: []byte(`{"registration_ids":["ABC"]}`)})
	_, err := conn.Sender.Send(gcm.NewMessage(payload, ""), sendRetries)
	if err != nil {

		log.WithFields(log.Fields{
			"module": "GCM",
			"err":    err,
		}).Error("Error sending ping message")

		return err
	}
	return nil
}
开发者ID:cosminrentea,项目名称:guble,代码行数:17,代码来源:gcm_connector.go


示例11: gcmNotify

func gcmNotify(att string, msg string, errHandle *[]string, wg *sync.WaitGroup) (status bool) {
	status = true
	d := map[string]interface{}{"message": msg}
	sender := &gcm.Sender{ApiKey: gcmauth}
	data := gcm.NewMessage(d, att)
	_, err := sender.Send(data, 0)
	if err != nil {
		status = false
	}
	wg.Done()
	if status == false {
		*errHandle = append(*errHandle, att)
	}
	return
}
开发者ID:SteinWord,项目名称:gotification,代码行数:15,代码来源:gotification.go


示例12: pushNotificationAndroid

func pushNotificationAndroid(req RequestGaurunNotification) bool {
	LogError.Debug("START push notification for Android")

	data := map[string]interface{}{"message": req.Message}
	if len(req.Extend) > 0 {
		for _, extend := range req.Extend {
			data[extend.Key] = extend.Value
		}
	}

	msg := gcm.NewMessage(data, req.Tokens...)
	msg.CollapseKey = req.CollapseKey
	msg.DelayWhileIdle = req.DelayWhileIdle
	msg.TimeToLive = req.TimeToLive

	stime := time.Now()
	resp, err := GCMClient.SendNoRetry(msg)
	etime := time.Now()
	ptime := etime.Sub(stime).Seconds()
	if err != nil {
		atomic.AddInt64(&StatGaurun.Android.PushError, 1)
		for i, token := range req.Tokens {
			LogPush(req.IDs[i], StatusFailedPush, token, ptime, req, err)
		}
		return false
	}

	if resp.Failure > 0 {
		atomic.AddInt64(&StatGaurun.Android.PushSuccess, int64(resp.Success))
		atomic.AddInt64(&StatGaurun.Android.PushError, int64(resp.Failure))
		if len(resp.Results) == len(req.Tokens) {
			for i, token := range req.Tokens {
				if resp.Results[i].Error != "" {
					LogPush(req.IDs[i], StatusFailedPush, token, ptime, req, errors.New(resp.Results[i].Error))
				}
			}
		}
		return true
	}

	for i, token := range req.Tokens {
		LogPush(req.IDs[i], StatusSucceededPush, token, ptime, req, nil)
	}
	StatGaurun.Android.PushSuccess += int64(len(req.Tokens))
	LogError.Debug("END push notification for Android")
	return true
}
开发者ID:r-fujiwara,项目名称:gaurun,代码行数:47,代码来源:notification.go


示例13: broadcastMessage

func (conn *GCMConnector) broadcastMessage(msg *server.MessageForRoute) {
	topic := msg.Message.Path
	payload := conn.parseMessageToMap(msg.Message)
	log.WithFields(log.Fields{
		"module":         "GCM",
		"topic":          string(topic),
		"channel_length": len(conn.routerC),
	}).Debug("Broadcasting message with ")

	subscriptions := conn.kvStore.Iterate(registrationsSchema, "")
	count := 0
	for {
		select {
		case entry, ok := <-subscriptions:
			if !ok {
				log.WithFields(log.Fields{
					"module":          "GCM",
					"receivers_count": count,
				}).Info("Sent to message to ")
				return
			}
			gcmID := entry[0]
			//TODO collect 1000 gcmIds and send them in one request!
			broadcastMessage := gcm.NewMessage(payload, gcmID)
			go func() {
				//TODO error handling of response!
				_, err := conn.Sender.Send(broadcastMessage, broadcastRetries)
				log.WithFields(log.Fields{
					"module": "GCM",
					"gcmID":  gcmID,
				}).Debug("Sent broadcast message to")
				if err != nil {

					log.WithFields(log.Fields{
						"module": "GCM",
						"gmcId":  gcmID,
						"err":    err,
					}).Error("Error sending broadcast message to")
				}
			}()
			count++
		}
	}
}
开发者ID:cosminrentea,项目名称:guble,代码行数:44,代码来源:gcm_connector.go


示例14: pushAndroid

func (this *CommandMsg) pushAndroid(server *Server) {
	registration_ids, registration_ids_ok := this.Command["registration_ids"]

	if !registration_ids_ok {
		log.Println("Registration ID(s) not provided!")
		return
	}

	msg, err := this.formatMessage()
	if err != nil {
		log.Println("Could not format message")
		return
	}

	data := map[string]interface{}{"event": msg.Event, "data": msg.Data, "time": msg.Time}

	regIDs := strings.Split(registration_ids, ",")
	gcmMessage := gcm.NewMessage(data, regIDs...)

	sender := server.GetGCMClient()

	server.Stats.LogGCMPush()
	gcmResponse, gcmErr := sender.Send(gcmMessage, 2)
	if gcmErr != nil {
		server.Stats.LogGCMError()
		log.Printf("Error (Android): %s\n", gcmErr)
		return
	}

	if gcmResponse.Failure > 0 {
		server.Stats.LogGCMFailure()
		if !server.Config.GetBool("redis_enabled") {
			log.Println("Could not push to android_error_queue since redis is not enabled")
			return
		}

		failurePayload := map[string]interface{}{"registration_ids": regIDs, "results": gcmResponse.Results}

		msg_str, _ := json.Marshal(failurePayload)
		server.Store.redis.Push(server.Config.Get("android_error_queue"), string(msg_str))
	}
}
开发者ID:se77en,项目名称:incus,代码行数:42,代码来源:message.go


示例15: CreateNotif

func CreateNotif(card me.CardModel, ts int) {
	if notif, ok := db.Notif[card.NotifId]; ok {
		if client, okk := db.User[notif.ClientId]; okk {
			data := map[string]interface{}{"title": notif.Name, "id": card.Id}
			regIDs := []string{client.RegId}
			msg := gcm.NewMessage(data, regIDs...)

			// Create a Sender to send the message.
			sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}

			// Send the message and receive the response after at most two retries.
			_, err := sender.Send(msg, 2)
			if err != nil {
				fmt.Println("Failed to send message: %v", err)
			} else {
				fmt.Println("Message is sent.")
			}
		}
	}
}
开发者ID:btasdoven,项目名称:Notifier,代码行数:20,代码来源:server.go


示例16: sendMessage

func (conn *GCMConnector) sendMessage(msg *server.MessageForRoute) {
	gcmID := msg.Route.ApplicationID

	payload := conn.parseMessageToMap(msg.Message)

	var messageToGcm = gcm.NewMessage(payload, gcmID)

	log.WithFields(log.Fields{
		"module":         "GCM",
		"gcmID":          gcmID,
		"channel_length": len(conn.routerC),
	}).Debug("Sending message to ")

	result, err := conn.Sender.Send(messageToGcm, sendRetries)
	if err != nil {
		log.WithFields(log.Fields{
			"module": "GCM",
			"gcmID":  gcmID,
			"err":    err,
		}).Error("Error sending message to")

		return
	}

	errorJSON := result.Results[0].Error
	if errorJSON != "" {
		conn.handleJSONError(errorJSON, gcmID, msg.Route)
	} else {
		log.WithFields(log.Fields{
			"module":    "GCM",
			"gcmID":     gcmID,
			"errorJSON": errorJSON,
		}).Debug("Delivered message to ")
	}

	// we only send to one receiver,
	// so we know that we can replace the old id with the first registration id (=canonical id)
	if result.CanonicalIDs != 0 {
		conn.replaceSubscriptionWithCanonicalID(msg.Route, result.Results[0].RegistrationID)
	}
}
开发者ID:cosminrentea,项目名称:guble,代码行数:41,代码来源:gcm_connector.go


示例17: PushIt

func PushIt(w http.ResponseWriter, r *http.Request) error {
	c := appengine.NewContext(r)
	req := &FormData{}
	json.NewDecoder(r.Body).Decode(&req)

	client := urlfetch.Client(c)
	sender := &gcm.Sender{ApiKey: req.APIKey, Http: client}

	// Create the message to be sent.
	data := map[string]interface{}{"data": req.Message}
	regIDs := []string{req.RegId}
	msg := gcm.NewMessage(data, regIDs...)

	// Send the message and receive the response after at most two retries.
	_, err := sender.Send(msg, 2)
	if err != nil {
		result := &Result{Message: "Failed to send message: " + err.Error()}
		return json.NewEncoder(w).Encode(result)
	}
	result := &Result{Message: "Successfully sent"}
	return json.NewEncoder(w).Encode(result)
}
开发者ID:LOG-TAG,项目名称:push,代码行数:22,代码来源:server.go


示例18: pushNotificationAndroid

func pushNotificationAndroid(req gaurun.RequestGaurunNotification) bool {
	data := map[string]interface{}{"message": req.Message}
	msg := gcm.NewMessage(data, req.Tokens...)
	msg.CollapseKey = req.CollapseKey
	msg.DelayWhileIdle = req.DelayWhileIdle
	msg.TimeToLive = req.TimeToLive

	sender := &gcm.Sender{ApiKey: gaurun.ConfGaurun.Android.ApiKey}
	sender.Http = new(http.Client)
	sender.Http.Timeout = time.Duration(gaurun.ConfGaurun.Android.Timeout) * time.Second

	resp, err := sender.SendNoRetry(msg)
	if err != nil {
		return false
	}

	if resp.Failure > 0 {
		return true
	}

	return true
}
开发者ID:justinlu,项目名称:gaurun,代码行数:22,代码来源:recover.go


示例19: send

func (this *Sender) send(users []auth.User, vote storage.Vote) {
	funcPrefix := "Sending notifications"
	log.Debug.Printf("%s: start\n", funcPrefix)
	defer log.Debug.Printf("%s: end\n", funcPrefix)

	var devices Devices

	log.Debug.Printf("%s: getting DevIds from users...\n", funcPrefix)
	for i := range users {
		log.Debug.Printf("%s: getting DevId from user %+v...\n", funcPrefix, users[i])
		switch users[i].Device {
		case DEVICE_IOS:
			devices.AppleIds = append(devices.AppleIds, users[i].DevId)
		case DEVICE_ANDROID:
			devices.GoogleIds = append(devices.GoogleIds, users[i].DevId)
		default:
			devices.OtherUsers = append(devices.OtherUsers, users[i])
		}
	}

	if len(devices.GoogleIds) > 0 {
		log.Debug.Printf("%s: trying to send Google device notifications to %v\n", funcPrefix, devices.GoogleIds)
		data := map[string]interface{}{"date": strconv.FormatInt(vote.Date, 10), "id": string(vote.Id), "name": string(vote.Name), "owner": string(vote.Owner), "voted": strconv.FormatBool(vote.Voted)}
		msg := gcm.NewMessage(data, devices.GoogleIds...)
		sender := &gcm.Sender{ApiKey: this.GoogleApiKey}
		_, err := sender.Send(msg, 2)
		if err != nil {
			log.Error.Printf("%s: sending notification to Google device failed: %s\n", funcPrefix, err.Error())
		}
	}

	if len(devices.AppleIds) > 0 {
		log.Debug.Printf("%s: Apple notification Server: %s, Cert: %s, Key: %s\n", funcPrefix, this.AppleServer, this.AppleCertPath, this.AppleKeyPath)
		apn, err := apns.NewClient(this.AppleServer, this.AppleCertPath, this.AppleKeyPath)
		apn.MAX_PAYLOAD_SIZE = 2048
		if err != nil {
			log.Error.Printf("%s: sending notification to Apple device failed: %s\n", funcPrefix, err.Error())
		} else {
			payload := &ApplePayload{}
			payload.Aps.Alert = vote.Name
			payload.Aps.Title = "MOC Pulse"
			payload.Aps.Category = "newVote"
			payload.Aps.Vote = vote
			actions := &SimulatorAction{}
			actions.Title = "Vote"
			actions.Identifier = "voteButtonAction"
			payload.SimulatorActions = append(payload.SimulatorActions, *actions)
			bytes, _ := json.Marshal(payload)
			log.Debug.Printf("%s: Apple notification payload: %v\n", funcPrefix, string(bytes))
			for i := range devices.AppleIds {
				log.Debug.Printf("%s: trying to send Apple device notification to %v\n", funcPrefix, devices.AppleIds[i])
				err = apn.SendPayloadString(devices.AppleIds[i], bytes, 5)
				if err != nil {
					log.Error.Printf("%s: sending notification to Apple device failed: %s\n", funcPrefix, err.Error())
				}
			}
		}
	}

	if len(devices.OtherUsers) > 0 {
		mandrill.Key = this.MandrillKey
		err := mandrill.Ping()
		if err != nil {
			log.Error.Printf("%s: sending notification to Email failed: %s\n", funcPrefix, err.Error())
		} else {
			data := make(map[string]string)
			data["QUESTION"] = vote.Name
			data["VOTE"] = vote.Id
			for i := range devices.OtherUsers {
				data["TOKEN"] = devices.OtherUsers[i].Id
				log.Debug.Printf("%s: trying to send Email notification to %v\n", funcPrefix, devices.OtherUsers[i].Email)
				msg := mandrill.NewMessageTo(devices.OtherUsers[i].Email, devices.OtherUsers[i].FirstName+devices.OtherUsers[i].LastName)
				msg.Subject = this.MandrillSubject
				msg.FromEmail = this.MandrillFromEmail
				msg.FromName = this.MandrillFromName
				_, err := msg.SendTemplate(this.MandrillTemplate, data, false)
				if err != nil {
					log.Error.Printf("%s: sending notification to Email failed: %s\n", funcPrefix, err.Error())
				}
			}
		}
	}
}
开发者ID:walkline,项目名称:MoC-pulse-backend,代码行数:83,代码来源:sender.go


示例20: sendMessageToGCM

func sendMessageToGCM(tokens []string, payload map[string]interface{}) (bool, error) {
	// At any exit, decrement pending
	defer func() {
		go decrementPending()
	}()

	if len(tokens) == 0 {
		errText := "No tokens were supplied, exiting"
		log.Println(errText)
		return false, errors.New(errText)
	}

	// if payloadAsString == "" {
	// 	errText := "Payload was empty, exiting"
	// 	log.Println(errText)
	// 	return false, errors.New(errText)
	// }

	// Unpack the JSON payload
	// var payload map[string]interface{}
	// err := json.Unmarshal([]byte(payloadAsString), &payload)
	// if err != nil {
	// 	log.Println("Can't unmarshal the json: " + err.Error())
	// 	log.Println("Original: " + payloadAsString)
	// 	return false, err
	// }

	// All is well, make & send the message
	go appendAttempts(len(tokens))

	msg := gcm.NewMessage(payload, tokens...)
	sender := &gcm.Sender{ApiKey: settings.GCMAPIKey}
	response, err := sender.Send(msg, 2)
	if err != nil {
		log.Println("Failed to send message:")
		log.Println(err.Error())

		go appendFailures(1)
		return false, err
	}

	numCan := 0
	numErr := 0
	if response != nil {
		for i, result := range response.Results {
			// Canonicals
			if result.RegistrationID != "" {
				numCan++
				canonicalReplacements = append(canonicalReplacements, canonicalReplacement{tokens[i], result.RegistrationID})
			}
			if result.Error != "" {
				numErr++
				log.Printf("Error sending: %s", result.Error)

				if result.Error == "NotRegistered" {
					handleNotRegisteredError(tokens[i])
					go appendNotRegistered(1)
				}
			}
		}

		go appendCanonicals(numCan)
		go appendFailures(numErr)
	}

	log.Printf("Message sent. Attempts: %d, Errors: %d, Successful: %d (Canonicals: %d)", len(tokens), numErr, len(tokens)-numErr, numCan)

	return true, nil
}
开发者ID:iamulya,项目名称:GoCM,代码行数:69,代码来源:utilities.go



注:本文中的github.com/alexjlockwood/gcm.NewMessage函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang assert.Equal函数代码示例发布时间:2022-05-24
下一篇:
Golang rest.ResponseWriter类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap