Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
1. go get github.com/googollee/go-gcm 2. go build TinyGCMServer.go 3. ./TinyGCMServer.go <API_KEY> <Server URL(:port)>
// +build !appengine
package main
/*
* Usage: ./TinyGCMServer <API_KEY> <Server URL(:port)>
* Test: curl -d "<NOTIFICATION MESSAGE>" http://serverURL/sendMessage?target=<REGISTRATION_ID>
*/
import (
"fmt"
gcm "github.com/googollee/go-gcm"
"io/ioutil"
"net/http"
"os"
)
var API_KEY string
func main() {
serverURL := "localhost:8000"
if len(os.Args) > 1 {
API_KEY = os.Args[1]
if len(os.Args) > 2 {
serverURL = os.Args[2]
}
http.HandleFunc("/sendMessage", sendMessageHandler)
fmt.Println("Notification server initialized.. : ", serverURL)
fmt.Println("API Key : ", API_KEY)
http.ListenAndServe(serverURL, nil)
}
}
func sendMessageHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
body, _ := ioutil.ReadAll(r.Body)
target := r.FormValue("target")
fmt.Fprintln(w, "target :", target)
fmt.Fprintln(w, "body :", string(body))
sendGCMNotification(target, string(body))
}
}
func sendGCMNotification(target string, message string) {
// API Key
client := gcm.New(API_KEY)
// client ID
load := gcm.NewMessage(target)
// load.AddRecipient("abc")
load.SetPayload("data", message)
// load.CollapseKey = "registerCar"
load.DelayWhileIdle = true
load.TimeToLive = 10
resp, err := client.Send(load)
fmt.Printf("id: %+v\n", resp)
fmt.Println("err:", err)
fmt.Println("err index:", resp.ErrorIndexes())
fmt.Println("reg index:", resp.RefreshIndexes())
}