Get the total price from the API

This commit is contained in:
palo 2023-11-07 20:08:40 +01:00
parent bc26e2029a
commit f74ce8de7a
4 changed files with 76 additions and 5 deletions

6
api.go
View File

@ -33,13 +33,17 @@ type GetPizzasCommand struct {
// What to receive from the API
type JSONReceived interface {
ReceivePizzas
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

26
main.go
View File

@ -10,7 +10,7 @@ import (
)
var (
templates = template.Must(template.ParseFiles("templates/index.html", "templates/pizza.html"))
templates = template.Must(template.ParseFiles("templates/index.html", "templates/pizza.html", "templates/ordered.html"))
)
type Pizza struct {
@ -53,7 +53,8 @@ func printHandler(w http.ResponseWriter, r *http.Request) {
/**
* Handler function for "/pizza", only accepts POST requests
*
* Tells the API to print the pizza order specified in its Form
* Tells the API to print the pizza order specified in its Form, then receive
* back the correct price and return a formatted HTML page
*/
func pizzaHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@ -73,14 +74,31 @@ func pizzaHandler(w http.ResponseWriter, r *http.Request) {
}
json_command := PizzaCommand{Command: "pizza", Pizzas: pizzas}
_, err := sendJSONToServer(nil, json_command)
socket, err := sendJSONToServer(nil, json_command)
if err != nil {
fmt.Fprintf(w, "Error while connecting to the printer server")
return
}
http.Redirect(w, r, "/order_pizzas", http.StatusSeeOther)
price := ReceivePrice{}
_, err = receiveJSONFromServer(socket, &price)
if err != nil {
fmt.Fprintf(w, "Error while connecting to the printer server")
return
}
// pass the order data to the HTML
order := struct {
Pizzas []Pizza
TotalPrice int
}{
pizzas,
price.TotalPrice,
}
templates.ExecuteTemplate(w, "ordered.html", order)
}
/**

38
templates/ordered.html Normal file
View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>Scontrini</title>
<link rel="stylesheet" href="">
</head>
<body>
<h1>ORDINE</h1>
<h3>Il tuo ordine è stato stampato</h3>
<table id="pizzas">
<tr>
<td>
Nome
</td>
<td>
Quantità
</td>
</tr>
{{ range .Pizzas }}
<tr>
<td>
{{ .Name }}
</td>
<td>
{{ .Quantity }}
</td>
</tr>
{{ end }}
</table>
<p id="total_price">Prezzo totale: {{ .TotalPrice }}</p>
<button><a href="/">Stampa qualcosa</a></button>
</body>
</html>

View File

@ -11,6 +11,17 @@
<form action="/pizza" method="post">
<table id="pizzas">
<tr>
<td>
Nome
</td>
<td>
Prezzo
</td>
<td>
Quantità
</td>
</tr>
{{ range . }}
<tr>
<td>