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

// Package websocket sets up websocket connections with clients and allows live reactor readouts.
package websocket
// creates websocket server and upgrades incoming connections
import (
"encoding/json"
"fmt"
"net/http"
ws "github.com/gorilla/websocket"
)
type ReactorTest struct {
Id int `json:"id"`
Name string `json:"name"`
}
type WebSocket struct {
// dummy struct for interface
N string
}
func New() *WebSocket {
return &WebSocket{}
}
func (s *WebSocket) Start() {
fmt.Println("Starting ws server!")
setupRoutes()
http.ListenAndServe(":8080", nil)
}
// default opts allow all origins
var upgrader = ws.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
// reader
func reader(conn *ws.Conn) {
for {
// read forever
//messageType, p, err := conn.ReadMessage()
_, p, err := conn.ReadMessage()
if err != nil {
if ws.IsCloseError(err, ws.CloseNormalClosure, ws.CloseGoingAway) {
// normally closed
return
}
panic(err)
}
fmt.Printf("Msg: %s\n", string(p))
}
}
func serverWs(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Host)
websocket, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
// 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)
if err != nil {
panic(err)
}
// pass to connection
if err := websocket.WriteMessage(ws.TextMessage, msg); err != nil {
panic(err)
}
// pass to reader
reader(websocket)
}
func setupRoutes() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Simple Server")
})
http.HandleFunc("/ws", serverWs)
}