You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
1.7 KiB
Go
91 lines
1.7 KiB
Go
2 years ago
|
// Package websocket sets up websocket connections with clients and allows live reactor readouts.
|
||
2 years ago
|
package websocket
|
||
|
|
||
|
// creates websocket server and upgrades incoming connections
|
||
|
import (
|
||
2 years ago
|
"encoding/json"
|
||
2 years ago
|
"fmt"
|
||
|
"net/http"
|
||
|
|
||
|
ws "github.com/gorilla/websocket"
|
||
|
)
|
||
|
|
||
2 years ago
|
type ReactorTest struct {
|
||
|
Id int `json:"id"`
|
||
|
Name string `json:"name"`
|
||
|
}
|
||
|
|
||
|
type WebSocket struct {
|
||
2 years ago
|
// dummy struct for interface
|
||
|
N string
|
||
|
}
|
||
|
|
||
2 years ago
|
func New() *WebSocket {
|
||
|
return &WebSocket{}
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
func (s *WebSocket) Start() {
|
||
2 years ago
|
fmt.Println("Starting ws server!")
|
||
|
setupRoutes()
|
||
|
http.ListenAndServe(":8080", nil)
|
||
|
}
|
||
|
|
||
2 years ago
|
// default opts allow all origins
|
||
2 years ago
|
var upgrader = ws.Upgrader{
|
||
|
CheckOrigin: func(r *http.Request) bool { return true },
|
||
|
}
|
||
|
|
||
|
// reader
|
||
|
func reader(conn *ws.Conn) {
|
||
|
|
||
|
for {
|
||
|
// read forever
|
||
2 years ago
|
//messageType, p, err := conn.ReadMessage()
|
||
|
_, p, err := conn.ReadMessage()
|
||
2 years ago
|
|
||
2 years ago
|
if err != nil {
|
||
|
if ws.IsCloseError(err, ws.CloseNormalClosure, ws.CloseGoingAway) {
|
||
|
// normally closed
|
||
|
return
|
||
|
}
|
||
2 years ago
|
panic(err)
|
||
|
}
|
||
2 years ago
|
fmt.Printf("Msg: %s\n", string(p))
|
||
2 years ago
|
}
|
||
|
}
|
||
|
|
||
|
func serverWs(w http.ResponseWriter, r *http.Request) {
|
||
|
fmt.Println(r.Host)
|
||
|
|
||
2 years ago
|
websocket, err := upgrader.Upgrade(w, r, nil)
|
||
2 years ago
|
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
|
||
2 years ago
|
// try sending reactor
|
||
2 years ago
|
t1 := &ReactorTest{Id: 1111, Name: "test1"}
|
||
|
t2 := &ReactorTest{Id: 1112, Name: "test2"}
|
||
|
t3 := &ReactorTest{Id: 1113, Name: "test3"}
|
||
|
n := []*ReactorTest{t1, t2, t3}
|
||
|
msg, err := json.Marshal(n)
|
||
2 years ago
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
// pass to connection
|
||
|
if err := websocket.WriteMessage(ws.TextMessage, msg); err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
|
||
2 years ago
|
// pass to reader
|
||
2 years ago
|
reader(websocket)
|
||
2 years ago
|
}
|
||
|
|
||
|
func setupRoutes() {
|
||
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||
|
fmt.Fprintf(w, "Simple Server")
|
||
|
})
|
||
|
|
||
|
http.HandleFunc("/ws", serverWs)
|
||
|
}
|