Scontrini-Web-Client/api.go

111 lines
2.2 KiB
Go

package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
)
var (
printer_server_IP = net.ParseIP("127.0.0.1")
printer_server_port = 4444
)
// Commands to give to the API
type JSONCommand interface {
PrintCommand | PizzaCommand | GetPizzasCommand
}
type PrintCommand struct {
Command string `json:"command"`
Text string `json:"text"`
}
type PizzaCommand struct {
Command string `json:"command"`
Pizzas []Pizza `json:"pizzas"`
}
type GetPizzasCommand struct {
Command string `json:"command"`
}
// What to receive from the API
type JSONReceived interface {
ReceivePizzas | ReceivePrice
}
type ReceivePizzas struct {
Pizzas []Pizza `json:"pizzas"`
}
type ReceivePrice struct {
TotalPrice int `json:"total_price"`
}
/**
* All messages from and to the API must have the first 4 bytes set to represent
* the length of the message, followed by the message itself
*/
func sendJSONToServer[T JSONCommand](socket *net.TCPConn, json_command T) (*net.TCPConn, error) {
json_data, err := json.Marshal(json_command)
if err != nil {
return nil, err
}
// in case a socket doesn't already exist create a new one
if socket == nil {
socket, err = net.DialTCP("tcp4", nil, &net.TCPAddr{printer_server_IP, printer_server_port, ""})
}
if err != nil {
return nil, err
}
// the first 4 bytes must be the length of the message
to_send := make([]byte, 4)
binary.LittleEndian.PutUint32(to_send, uint32(len(json_data)))
to_send = append(to_send, json_data...)
socket.Write([]byte(to_send))
return socket, nil
}
func receiveJSONFromServer[T JSONReceived](socket *net.TCPConn, json_received *T) (*net.TCPConn, error) {
var err error
// in case a socket doesn't already exist create a new one
if socket == nil {
fmt.Println("nil")
socket, err = net.DialTCP("tcp4", nil, &net.TCPAddr{printer_server_IP, printer_server_port, ""})
}
if err != nil {
return nil, err
}
// the first 4 bytes are the length of the message
b := make([]byte, 4)
_, err = socket.Read(b[0:])
if err != nil {
return nil, err
}
body_length := binary.LittleEndian.Uint32(b)
body := make([]byte, body_length)
_, err = socket.Read(body[0:])
err = json.Unmarshal(body, json_received)
if err != nil {
return nil, err
}
return socket, nil
}