기본 콘텐츠로 건너뛰기

go로 android notification server를 만들었다.

내가 처한 갑갑한 상황은 이런 것이었다.

1. Android 용 notification server + client 를 구현해야한다.
2. 서비스 서버는 내가 손을 댈수 없지만 windows+asp 기반으로 되어있다.
3. 내 컴퓨터는 OS X다 (....)
4. 소스가 노출되는 형태의 결과물은 안된다(script류 X)
5. 서버 구동을 위해 별도의 프로그램을 설치할 수 없다 (java 안됨)
6. exe 파일을 만들어야한다. 그것도 OS X에서
7. C/C++로?
8. 테스트 용으로 디플로이도 해야할 것 같다.

그래서 떠올린 것이 go.
유지보수도 겸해서 천치도 읽을 수 있게 짜고 싶었다.

go-gcm package를 일단 써서 후지고 빠르게 만들자.
https://gist.github.com/acidsound/5121536#file-tinygcmserver-go


// +build !appengine
package main
 
/*
* Usage: ./TinyGCMServer.go <API_KEY> <Server URL(:port)>
* Test: curl -d "<NOTIFICATION MESSAGE>" http://serverURL/sendMessage?target=<REGISTRATION_ID>
*/
import (
"fmt"
"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())
}


코드를 다 짜고 난 다음 실행해보고 생각보다 잘돌아가서 만족
말로 만들었던 크로스 컴파일에 도전.

먼저 
$ cd /usr/local/go/src/
$ sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean

컴파일 돌렸다.
만일 리눅스 바이너리를 만들려면 
$ sudo GOOS=linux GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean

뭐 이러면 될듯.
컴파일이 끝나면
---
Installed Go for windows/386 in /usr/local/go
Installed commands in /usr/local/go/bin
$

요렇게 떨어질 것이다.
다음은 exe 파일을 만들어보자.

$ GOOS=windows GOARCH=386 go build -o appname.exe appname.go

이럴려고 컴파일 한거니까.
오오 진정 exe 파일을 제가 만들었단 말입니까!

윈도우에서도 잘 돌아갈 것이다.
단 curl 류를 사용한다면 cmd 에서 codepage를 주의할 것.

댓글

  1. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
    GCM 전반적인 개발에 대한 내용. 그림이 있어서 일단 추가

    답글삭제
  2. POST대신 GET으로 변경하고 좀 더 단순화한 소스를 gist에 올렸습니다.
    https://gist.github.com/acidsound/5424720

    답글삭제

댓글 쓰기

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.