tu-wien
/
kerma
Archived
2
0
Fork 0
This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
kerma/utils/handler.go

90 lines
2.0 KiB
Go

// Package utils provides utilities that are needed for the functioning of Kerma
package utils
import (
"errors"
"kerma/helpers"
"kerma/models"
"net"
"strconv"
"github.com/docker/go/canonical/json"
)
/*
A TCPHandler is a struct used for communicating with other Kerma nodes/clients
It consists of:
- Conn - a connection for sending and receiving requests
- Logger
- Config - the configuration of the application
*/
type TCPHandler struct {
Conn net.Conn
Logger helpers.Logger
Config helpers.Config
}
/*
Construct creates a new handler on the specified connection
*/
func (h *TCPHandler) Construct(conn net.Conn) {
h.Conn = conn
h.Config.Construct()
}
/*
Output handles outgoing data in a canonical JSON format
*/
func (h *TCPHandler) Output(respJSON []byte) {
h.Logger.Info("OUT: " + h.GetRemotePeer() + " " + string(respJSON))
respJSON = append(respJSON, '\n')
h.Conn.Write(respJSON)
}
/*
Error handles outgoing errors in a canonical JSON format
*/
func (h *TCPHandler) Error(errorMsg string) {
var resp models.Error
resp.Construct(errorMsg)
respJSON, _ := resp.MarshalJson()
h.Output(respJSON)
}
/*
Fail handles outgoing errors in a canonical JSON format and terminates the connection
*/
func (h *TCPHandler) Fail(errorMsg string) {
h.Error(errorMsg)
h.Conn.Close()
}
/*
Input handles input data in a canonical JSON format
*/
func (h *TCPHandler) Input(in []byte) (map[string](interface{}), error) {
var msg map[string](interface{})
err := json.Unmarshal(in, &msg)
if err != nil {
h.Logger.Error("Failed decoding message " + err.Error())
return nil, errors.New("failed decoding message")
}
return msg, nil
}
/*
GetRemotePeer returns tha address of the remote peer as a string
*/
func (h *TCPHandler) GetRemotePeer() string {
return h.Conn.RemoteAddr().String()
}
/*
GetLocalPeer returns the address + port combination of the local peer as a string
*/
func (h *TCPHandler) GetLocalPeer() string {
return h.Config.IPAddress + ":" + strconv.Itoa(h.Config.Port)
}