LoginSignup
6
6

More than 5 years have passed since last update.

Gojiを使ってWebビーコン作る

Last updated at Posted at 2015-05-29

業務でWebビーコン作る事になって折角なのでーということでGO言語使って実装してみることにした。

実際にやること

Content-Typeimage/gifなどの画像を追加して表示側では1pxの画像として配置してもらう。

表示側の中身

index.php
<?php
setcookie("value", "適当なCookieの値");
setcookie("expire", time()+3600*24*20);
session_start();
$_SESSION['customer_id'] = 184;
$_SESSION['counter'] = $_SESSOIN['counter'] ? $_SESSION['counter'] + 1 : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <div class="container">
    <div class="title">
      <h1>Test Title</h1>
    </div>
    <div class="body">
      <p>この下にビーコンのImageタグが入ります。</p>
      <img src="http://localhost:9090/image.gif" style="width:1px;height:1px;">
      <p>ビーコンからCookieやSessionが取れるかどうかのテスト</p>
    </div>
    <div class="footer"><span>Footer</span></div>
  </div>
</body>
</html>

サーバサイド側の中身

server.go
package main
import (
  "fmt"
  "flag"
  "net/http"
  "github.com/zenazn/goji"
  "github.com/zenazn/goji/web"
)

func handlerImage(c web.C, w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "image/gif")
  for _, cookie := range r.Cookies() {
    fmt.Println(cookie.Name, cookie.Value)
  }
}

func main(){
  flag.Set("bind", ":9090")
  goji.Get("/image.gif", handlerImage)
  goji.Serve()
}

interfaceとかtype辺りはまだ理解しきってない。その内徐々にアップデートしていく予定。
go run server.goで起動。

2015/05/29 17:16:59.870388 [] Started GET "/image.gif" from 127.0.0.1:60637
PHPSESSID 7c9ee766d94e4f25235e2512d376a870
value %E9%81%A9%E5%BD%93%E3%81%AACookie%E3%81%AE%E5%80%A4
expire 1434615419
2015/05/29 17:16:59.870453 [] Returning 200 in 33.831µs

33.831μsなんて!素敵!!
流石にPHPのセッションまでは取得出来なかった。SessionIDまではとれたけどね…Sessionはまだ頑張ってみる。

ハマった事

Gojiのポートを変える

$GOPATH/src/github.com/zenazn/goji/bind/bind.goWithFlag()メソッド内でflag.StringVarを呼び出しているので

flag.Set("bind", ":9090")

で、設定するとポートが変更出来た。結構悩んだ。

Cookieを取得する

WebビーコンなのでCookieからデータを取得したい。

r.Header

上記の様にHeaderを取得すればCookie自体も取得出来たけどテキストデータなので純粋にCookieデータを取得したい。
net/http/cookiejarでCookieを自由に変更出来るとの事だったんだけど値をセットする際に利用するので違った模様。
net/httpパッケージの中にCookiesというメソッドがあったので利用してみたら

for _, cookie := range r.Cookies() {
  fmt.Println(cookie.Name, cookie.Value)
}

こんな感じで簡単に出来た。

参考したURLなど

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6