Almost ready backend of cart
This commit is contained in:
@@ -192,6 +192,83 @@ func checkPayHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Write([]byte(response))
|
w.Write([]byte(response))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CartItem struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Price float64 `json:"price"`
|
||||||
|
Quantity int `json:"quantity"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Cart struct {
|
||||||
|
CartItems []CartItem `json:"cart_items"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func add_to_cart(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
cartCookie, err := r.Cookie("cart")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Cart cookie not found", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Print("cartCookie.Value: ", cartCookie.Value)
|
||||||
|
var cart Cart
|
||||||
|
|
||||||
|
// Разбираем JSON
|
||||||
|
err = json.Unmarshal([]byte(cartCookie.Value), &cart)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Ошибка при разборе JSON:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
del_cookie, err := r.Cookie("uuid")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Не найден cookie с uuid", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
total_cookie, err := r.Cookie("total_price")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Не найден cookie с total_price", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
total_price := total_cookie.Value
|
||||||
|
order_id := del_cookie.Value
|
||||||
|
|
||||||
|
insertSql := `INSERT INTO order_list VALUES (?, ?, ?)`
|
||||||
|
_, err = db.Exec(insertSql, order_id, total_price, time.Now().Format("2006-01-02 15:04:05"))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range cart.CartItems {
|
||||||
|
|
||||||
|
insertSQL := `INSERT INTO order_lines VALUES (?, ?, ?, ?, ?)`
|
||||||
|
_, err = db.Exec(insertSQL, order_id, item.ID, item.Title, item.Price, item.Quantity)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insertSQL := `DELETE FROM url_pays WHERE uuid = ?`
|
||||||
|
// _, err = db.Exec(insertSQL, del_cookie.Value)
|
||||||
|
// if err != nil {
|
||||||
|
// http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// // Clear uuid cookie
|
||||||
|
// del_cookie = &http.Cookie{
|
||||||
|
// Name: "uuid",
|
||||||
|
// Value: "",
|
||||||
|
// MaxAge: -1,
|
||||||
|
// }
|
||||||
|
// http.SetCookie(w, del_cookie)
|
||||||
|
|
||||||
|
// Send success response
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
w.Write([]byte("OK"))
|
||||||
|
}
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
initDB()
|
initDB()
|
||||||
@@ -206,6 +283,7 @@ func main() {
|
|||||||
// Register handlers
|
// Register handlers
|
||||||
http.HandleFunc("/api/pay", payHandler)
|
http.HandleFunc("/api/pay", payHandler)
|
||||||
http.HandleFunc("/api/check_pay", checkPayHandler)
|
http.HandleFunc("/api/check_pay", checkPayHandler)
|
||||||
|
http.HandleFunc("/api/add_to_cart", add_to_cart)
|
||||||
|
|
||||||
// Start server with CORS middleware
|
// Start server with CORS middleware
|
||||||
port := os.Getenv("PORT")
|
port := os.Getenv("PORT")
|
||||||
@@ -216,3 +294,60 @@ func main() {
|
|||||||
fmt.Println("Go-сервер запущен на порту", port)
|
fmt.Println("Go-сервер запущен на порту", port)
|
||||||
log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux)))
|
log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// package main
|
||||||
|
|
||||||
|
// import (
|
||||||
|
// "encoding/json"
|
||||||
|
// "fmt"
|
||||||
|
// )
|
||||||
|
|
||||||
|
// // Subscriber представляет структуру одного подписчика
|
||||||
|
// type Subscriber struct {
|
||||||
|
// Email string `json:"email"`
|
||||||
|
// Name string `json:"name"`
|
||||||
|
// Phone string `json:"phone"`
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // Subscribers представляет структуру всего JSON-объекта
|
||||||
|
// type Subscribers struct {
|
||||||
|
// Subscribers []Subscriber `json:"subscribers"`
|
||||||
|
// }
|
||||||
|
|
||||||
|
// func main() {
|
||||||
|
// // Пример JSON-данных
|
||||||
|
// jsonData := `{
|
||||||
|
// "subscribers" : [
|
||||||
|
// {
|
||||||
|
// "email" : "somemail@gmail.com",
|
||||||
|
// "name" : "Maksim",
|
||||||
|
// "phone" : "80-77-524-2432"
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// "email" : "someAnotherMail@gmail.com",
|
||||||
|
// "name" : "Sasha",
|
||||||
|
// "phone" : ""
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// "email" : "someAnotherMail_1@gmail.com",
|
||||||
|
// "name" : "NoName",
|
||||||
|
// "phone" : ""
|
||||||
|
// }
|
||||||
|
// ]
|
||||||
|
// }`
|
||||||
|
|
||||||
|
// // Создаем переменную для хранения разобранных данных
|
||||||
|
// var subscribers Subscribers
|
||||||
|
|
||||||
|
// // Разбираем JSON
|
||||||
|
// err := json.Unmarshal([]byte(jsonData), &subscribers)
|
||||||
|
// if err != nil {
|
||||||
|
// fmt.Println("Ошибка при разборе JSON:", err)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // Выводим данные
|
||||||
|
// for _, subscriber := range subscribers.Subscribers {
|
||||||
|
// fmt.Printf("Email: %s, Name: %s, Phone: %s\n", subscriber.Email, subscriber.Name, subscriber.Phone)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
@@ -7,21 +7,31 @@ export interface CartItem {
|
|||||||
quantity: number;
|
quantity: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сохранить корзину в cookies
|
interface Cart {
|
||||||
|
cart_items: CartItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save cart to cookies
|
||||||
export const saveCart = (cartItems: CartItem[]): void => {
|
export const saveCart = (cartItems: CartItem[]): void => {
|
||||||
const cartData = JSON.stringify(cartItems);
|
const cart: Cart = {
|
||||||
Cookies.set('cart', cartData, { expires: 7 }); // Срок хранения cookies 7 дней
|
cart_items: cartItems
|
||||||
|
};
|
||||||
|
const cartData = JSON.stringify(cart);
|
||||||
|
Cookies.set('cart', cartData, { expires: 7 });
|
||||||
};
|
};
|
||||||
|
|
||||||
// Получить корзину из cookies
|
// Get cart from cookies
|
||||||
export const getCart = (): CartItem[] => {
|
export const getCart = (): CartItem[] => {
|
||||||
const cartData = Cookies.get('cart');
|
const cartData = Cookies.get('cart');
|
||||||
return cartData ? JSON.parse(cartData) : []; // Возвращаем пустой массив, если корзина не найдена
|
if (!cartData) return [];
|
||||||
|
|
||||||
|
const cart: Cart = JSON.parse(cartData);
|
||||||
|
return cart.cart_items;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Очистить корзину в cookies
|
// Clear cart in cookies
|
||||||
export const clearCart = (): void => {
|
export const clearCart = (): void => {
|
||||||
Cookies.remove('cart'); // Удаляем cookies с данными корзины
|
Cookies.remove('cart');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user