Skip to content

Instantly share code, notes, and snippets.

@acidsound
Last active December 14, 2015 17:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save acidsound/5121536 to your computer and use it in GitHub Desktop.
Save acidsound/5121536 to your computer and use it in GitHub Desktop.
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())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment