csvファイル形式でデータを送るのではなく、プログラムから直接データを放り込むプログラム
// main13.go
package main
import (
"flag"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
type GetLoc struct {
ID int `json:"id"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
TYPE string `json:"type"` // "PERSON","BUS","CONTROL
POPUP int `json:"popup"`
//Address string `json:"address"`
}
func echo2(w http.ResponseWriter, r *http.Request) {
conn2, err := upgrader.Upgrade(w, r, nil) //conn2でwebsocketを作成
if err != nil {
log.Println("websocket connection err:", err)
return
}
defer conn2.Close()
for {
gl2 := new(GetLoc)
gl2.ID = 101
gl2.Lat = 181.0
gl2.Lng = 181.0
gl2.TYPE = "BUS"
gl2.POPUP = 101
err := conn2.WriteJSON(&gl2)
if err != nil {
log.Println("ReadJSON:", err)
break
}
fmt.Println("echo2:", gl2)
time.Sleep(time.Second * 1)
}
}
var addr = flag.String("addr", "0.0.0.0:5000", "http service address") // テスト
func main() {
http.Handle("/", http.FileServer(http.Dir(".")))
http.HandleFunc("/echo2", echo2)
log.Println("server starting...", "http://localhost:5000")
log.Fatal(http.ListenAndServe("localhost:5000", nil))
}
index.htmlはこちら
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<form>
</form>
<script>
var ws;
// websocketのオープン(この段階で接続完了)
ws = new WebSocket('ws://localhost:5000/echo2') // ユーザ登録画面
ws.onopen = function (event) {
}
ws.onmessage = function (event) {
// データをJSON形式に変更
var obj = JSON.parse(event.data);
console.log("obj:",obj);
}
</script>
</body>
</html>