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.
86 lines
1.5 KiB
Go
86 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
const (
|
|
MSG_TYPE_AUTH string = "auth"
|
|
MSG_TYPE_SET_ID string = "set-id"
|
|
)
|
|
|
|
type AuthRequestClient struct {
|
|
conn *websocket.Conn
|
|
}
|
|
|
|
type AuthRequestProtocolMessage struct {
|
|
MessageType string `json:"type"`
|
|
Parameters map[string]string
|
|
}
|
|
|
|
func (c *AuthRequestClient) ReceiveRequest() (*AuthRequest, error) {
|
|
message, err := c.receiveProtocolMessage()
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if message.MessageType != MSG_TYPE_AUTH {
|
|
return nil, errors.New(
|
|
fmt.Sprintf(
|
|
"Wrong protocol message type, expected message of type \"%s\", got \"%s\"",
|
|
MSG_TYPE_AUTH,
|
|
message.MessageType,
|
|
),
|
|
)
|
|
}
|
|
|
|
instance, ok := message.Parameters["instance"]
|
|
|
|
if !ok {
|
|
return nil, errors.New("No \"instance\" parameter included in auth request parameters")
|
|
}
|
|
|
|
r := &AuthRequest{
|
|
Client: c,
|
|
Instance: instance,
|
|
}
|
|
|
|
return r, nil
|
|
}
|
|
|
|
func (c *AuthRequestClient) receiveProtocolMessage() (*AuthRequestProtocolMessage, error) {
|
|
_, message, err := c.conn.ReadMessage()
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var protocolMessage *AuthRequestProtocolMessage
|
|
|
|
err = json.Unmarshal(message, protocolMessage)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return protocolMessage, nil
|
|
}
|
|
|
|
func (c *AuthRequestClient) PropagateID(ID string) error {
|
|
message := &AuthRequestProtocolMessage{
|
|
MessageType: MSG_TYPE_SET_ID,
|
|
Parameters: map[string]string{
|
|
"id": ID,
|
|
},
|
|
}
|
|
|
|
err := c.conn.WriteJSON(message)
|
|
|
|
return err
|
|
}
|