Cleanup websocket implementation

This commit is contained in:
Dane Everitt 2019-04-20 11:59:28 -07:00
parent 1dfcebc746
commit 342c44abfb
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53

View File

@ -2,24 +2,24 @@ package main
import ( import (
"fmt" "fmt"
"github.com/gorilla/websocket"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
"go.uber.org/zap" "go.uber.org/zap"
"net/http" "net/http"
"strings"
) )
type WebsocketMessage struct { type WebsocketMessage struct {
// The action to perform. Should be one of the following that are supported: // The event to perform. Should be one of the following that are supported:
// //
// - status : Returns the server's power state. // - status : Returns the server's power state.
// - logs : Returns the server log data at the time of the request. // - logs : Returns the server log data at the time of the request.
// - power : Performs a power action aganist the server based the data. // - power : Performs a power action aganist the server based the data.
// - command : Performs a command on a server using the data field. // - command : Performs a command on a server using the data field.
Action string Event string `json:"event"`
// The data to pass along, only used by power/command currently. Other requests // The data to pass along, only used by power/command currently. Other requests
// should either omit the field or pass an empty string value as it is ignored. // should either omit the field or pass an empty value as it is ignored.
Data string Args []string `json:"args,omitempty"`
} }
func (rt *Router) routeWebsocket(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { func (rt *Router) routeWebsocket(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
@ -30,6 +30,8 @@ func (rt *Router) routeWebsocket(w http.ResponseWriter, r *http.Request, ps http
} }
defer c.Close() defer c.Close()
s := rt.Servers.Get(ps.ByName("server"))
for { for {
j := WebsocketMessage{} j := WebsocketMessage{}
@ -37,14 +39,14 @@ func (rt *Router) routeWebsocket(w http.ResponseWriter, r *http.Request, ps http
// specific socket request. If we did a break here the client would get disconnected // specific socket request. If we did a break here the client would get disconnected
// from the socket, which is NOT what we want to do. // from the socket, which is NOT what we want to do.
if err := c.ReadJSON(&j); err != nil { if err := c.ReadJSON(&j); err != nil {
continue break
} }
fmt.Printf("%s sent: %s = %s\n", c.RemoteAddr(), j.Action, j.Data) fmt.Printf("%s sent: %s = %s\n", s.Uuid, j.Event, strings.Join(j.Args, " "))
if err := c.WriteMessage(websocket.TextMessage, []byte("")); err != nil { if err := c.WriteJSON(WebsocketMessage{Event: j.Event, Args: []string{}}); err != nil {
zap.S().Warnw("error writing JSON to socket", zap.Error(err)) zap.S().Warnw("error writing JSON to socket", zap.Error(err))
continue break
} }
} }
} }