sinatra(시나트라) 는 rails 보다 가볍게 쓸 수 있는 라이브러리이다. 강성희님께 교육받던 중에 들었던 건데, 너무 어려워서 이름말고는 아무 것도 기억이 안났는데, 오늘 혹시나하고 써보니 생각보다 간편하게 된다 ㄷㄷㄷ
이걸로 오늘 뚝딱 만든게 바로 https://gcmsender.herokuapp.com/ 이다.
아래는 코드 설명이다.
먼저 루비는 깔려있어야 하니까 알아서 깔아야한다.
gem install gcm gem install sinatra
일단 gcm과 sinatra를 설치한다.
require 'sinatra' require 'gcm' # for production mode # set :port, 3002 # set :environment, :production get '/' do erb :index, :locals => {apiKey: '', regId: '', msg: ''} end put '/' do apiKey = params[:apiKey] || '' regIdStr = params[:regId] || '' msg = params[:msg] || '' if (!apiKey.empty? && !regIdStr.empty? && !msg.empty?) begin begin gcm = GCM.new(apiKey) regIDs= regIdStr.split(',') options = {data: JSON.parse(msg)} response = gcm.send_notification(regIDs, options) result = JSON.pretty_generate(response) rescue => error result = error end end else result = "error : fill all field" end erb :index, :locals => {apiKey: apiKey, regId: regIdStr, msg: msg, response: result } end
<!doctype html> <html> <head> <title>GCM Sender</title> <link href="/bootstrap.min.css" rel="stylesheet"> </head> <body class="span12"> <h1>GCM sender</h1> <form action="/" method="post" role="form"> <input type="hidden" name="_method" value="put" /> <div class="form-group"> <label for="apiKey">API Key(<a href="https://console.developers.google.com/project" target="_blank">Google Developer Console</a> - [project] - APIs&auth - Credentials - Key for server applications - API key)</label> <input id="apiKey" name="apiKey" value="<%= apiKey %>" placeholder="AIzaSyBRIejtalg7F3JaCKAg54C438u9ihfbhZk" class="form-control span12"/> </div> <br /> <div class="form-group"> <label for="regId">Reg IDs(<a href="http://developer.android.com/google/gcm/client.html#sample-register" target="_blank">google sample</a>, <a href="http://susemi99.kr/1012">my blog</a>)</label> <textarea id="regId" name="regId" placeholder="qwer, asdf, zxcv" class="form-control span12"><%= regId %></textarea> </div> <br /> <div class="form-group"> <label for="message">Message (JSON)</label> <textarea id="message" name="msg" placeholder='{"msg": "hello", "count": 34}' class="form-control span12"><%= msg %></textarea> </div> <br /> <button class="btn btn-default" type="submit">Send</button> </form> Result : <pre><%= response %></pre> </body> </html>
내가 짠 소스는 이게 전부다. html은 잘 몰라서 아마 리팩토링할 부분은 꽤 있을거라 생각이 든다.
더 이쁘게 만들기위한 bootstrap도 받아와서 public/bootstrap.min.css 에 넣어둔다.
ruby sender.rb
이라고 입력하면 서버가 실행된다.
localhost:4567 로 들어가면 이렇게 나온다.
source : https://github.com/susemi99/GCMSender