fedilogue/poll/cli.go

81 lines
1.7 KiB
Go

package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
"log"
"io"
"os"
)
func handleClient(commandClient net.Conn, runninginstances *[]RunningInstance, instanceReportChan chan InstanceReport) {
sizebyte := make([]byte, 4)
var commandmap CommandMap
var responseback ResponseBack
n, err := io.ReadFull(commandClient, sizebyte)
if n != 4 {
fmt.Println("Did not read 4 bytes, failure.")
os.Exit(1)
}
jsonsize := int(binary.LittleEndian.Uint32(sizebyte))
jsonbyte := make([]byte, jsonsize)
n, err = io.ReadFull(commandClient, jsonbyte)
if n != jsonsize {
fmt.Println("Failued to read json size of ", n)
os.Exit(1)
}
err = json.Unmarshal(jsonbyte, &commandmap)
if err != nil {
fmt.Println("Unable to unmarshal")
os.Exit(1)
}
switch commandmap.Type {
case "status":
responseback.Message = "Ok"
case "add":
log.Print("Manually added instance: " + commandmap.Endpoint)
var q InstanceReport
q.endpoint = commandmap.Endpoint
q.status = NEW_INSTANCE
instanceReportChan <- q
responseback.Message = "Added " + commandmap.Endpoint
case "suspend":
fmt.Println("Suspend")
case "resume":
fmt.Println("Resume")
default:
fmt.Println("Something else")
}
responseback.Type = "status"
responseback.RunningInstances = *runninginstances
responsebytes, err := json.Marshal(responseback)
if err != nil {
fmt.Println("Error: ", err)
os.Exit(1)
}
n = len(responsebytes)
binary.LittleEndian.PutUint32(sizebyte, uint32(n))
commandClient.Write(sizebyte)
responsebyte, err := json.Marshal(responseback)
if err != nil {
fmt.Println("Error response back: ", err)
os.Exit(1)
}
commandClient.Write(responsebyte)
commandClient.Close()
}