Golang: Send GCM - Google Cloud Message to Android Device

Share on:  
                 

alt

Assumption

  1. Go lang is installed in your computer
  2. Android sample application with GCM support

Step1: Generate server API key for GCM, This article will help you to generate server API key: [https://support.clevertap.com/docs/android/how-to-find-your-gcm-sender-id-and-gcm-api-server-key.html]

Step2: Install Go library for GCM

$ go get github.com/google/go-gcm

Step3: Write the following function in your main.go, replace server API key in the following function. You can provide multiple client tokens in “regIDs” in case, you would like to broadcast message to multiple devices.

func SendGCMToClient(pushText string,pushToken string){
       serverKey := "<YOUR SERVER API KEY>"
       var msg gcm.HttpMessage
       data := map[string]interface{}{"message":pushText}
       regIDs := []string{pushToken}
       msg.RegistrationIds = regIDs
       msg.Data = data
       response,err := gcm.SendHttp(serverKey,msg)
       if err != nil {
              mlog.Info(err.Error())
       }else{
              fmt.Println("Response ",response.Success)
              fmt.Println("MessageID ",response.MessageId)
              fmt.Println("Failure ",response.Failure)
              fmt.Println("Error ",response.Error)
              fmt.Println("Results ",response.Results)
       }
}

Step4: Call “SentGCMToClient” function from main function. replace client token in the following function

func main() {
       SendGMToClient("Hello from GCM","<Client Token>")
}

Step5: Compile & Run

go run main.go

Full Source code main.go

package main

import (
       "fmt"
       "github.com/google/go-gcm"
)

func main() {

       SendGMToClient("Hello from GCM","<CLIENT TOKEN>")
}

func SendGMToClient(pushText string,pushToken string){

       serverKey := "<YOUR SERVER KEY>"
       var msg gcm.HttpMessage

       data := map[string]interface{}{"message":pushText}
       regIDs := []string{pushToken}

       msg.RegistrationIds = regIDs
       msg.Data = data
       response,err := gcm.SendHttp(serverKey,msg)
       if err != nil {
              fmt.Println(err.Error())
       }else{
              fmt.Println("Response ",response.Success)
              fmt.Println("MessageID ",response.MessageId)
              fmt.Println("Failure ",response.Failure)
              fmt.Println("Error ",response.Error)
              fmt.Println("Results ",response.Results)

       }

}

go-gcm document:

https://godoc.org/github.com/google/go-gcm

Tags:   GOG C M