Compare commits
9 Commits
1e803b4beb
...
8ce139ff00
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ce139ff00 | |||
| 3158c8ff17 | |||
| 760169d766 | |||
| e46d1df00e | |||
| 47caa3a8a2 | |||
| 9e037a9c25 | |||
| 19b8f0716b | |||
| 09b545bf47 | |||
| 964f1411da |
BIN
frontend/style/app/UNITED.db
Normal file
BIN
frontend/style/app/UNITED.db
Normal file
Binary file not shown.
@@ -1,100 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"database/sql"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/gorilla/handlers"
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID int `json:"id"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var db *sql.DB
|
|
||||||
|
|
||||||
func initDB() {
|
|
||||||
var err error
|
|
||||||
dbFile := "users.db"
|
|
||||||
db, err = sql.Open("sqlite3", dbFile)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Ошибка подключения к базе данных:", err)
|
|
||||||
}
|
|
||||||
fmt.Println("База данных готова к работе.")
|
|
||||||
}
|
|
||||||
|
|
||||||
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("Received request with method: %s", r.Method)
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var user User
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
|
|
||||||
http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the email and password are provided
|
|
||||||
if user.Email == "" || user.Password == "" {
|
|
||||||
http.Error(w, "Email и пароль обязательны", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Query the database to check if the user exists
|
|
||||||
query := `SELECT id, email, password FROM users WHERE email = ?`
|
|
||||||
var dbUser User
|
|
||||||
err := db.QueryRow(query, user.Email).Scan(&dbUser.ID, &dbUser.Email, &dbUser.Password)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
// Если пользователь не найден, просим зарегистрироваться
|
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"message": "Пользователь не найден. Пожалуйста, зарегистрируйтесь."})
|
|
||||||
} else {
|
|
||||||
http.Error(w, "Ошибка при проверке учетных данных", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Если пользователь найден, проверяем пароль
|
|
||||||
if user.Password != dbUser.Password {
|
|
||||||
http.Error(w, "Неверный пароль", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Если пароль совпадает, вход успешен
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"message": "Вход успешен", "email": dbUser.Email})
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
initDB()
|
|
||||||
defer db.Close()
|
|
||||||
|
|
||||||
// Setup CORS
|
|
||||||
cors := handlers.CORS(
|
|
||||||
handlers.AllowedOrigins([]string{"*"}),
|
|
||||||
handlers.AllowedMethods([]string{"GET", "POST"}),
|
|
||||||
handlers.AllowedHeaders([]string{"Content-Type"}),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Register handlers
|
|
||||||
http.HandleFunc("/api/login", loginHandler)
|
|
||||||
|
|
||||||
// Start server with CORS middleware
|
|
||||||
port := os.Getenv("PORT")
|
|
||||||
if port == "" {
|
|
||||||
port = "8080"
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("Go-сервер запущен на порту", port)
|
|
||||||
log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux)))
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useState } from "react"
|
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
import { Button } from "@/components/ui/button"
|
|
||||||
import { Input } from "@/components/ui/input"
|
|
||||||
import { Label } from "@/components/ui/label"
|
|
||||||
import { useAuth } from "@/contexts/auth-context"
|
|
||||||
|
|
||||||
export default function LoginPage() {
|
|
||||||
const [email, setEmail] = useState("")
|
|
||||||
const [password, setPassword] = useState("")
|
|
||||||
const router = useRouter()
|
|
||||||
const { login } = useAuth()
|
|
||||||
|
|
||||||
const handleSubmit = (e: React.FormEvent) => {
|
|
||||||
e.preventDefault()
|
|
||||||
// In a real application, you would validate credentials here
|
|
||||||
login()
|
|
||||||
router.push("/")
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="container mx-auto px-4 py-8">
|
|
||||||
<h1 className="text-2xl font-bold mb-6">Войти</h1>
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4 max-w-md mx-auto">
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="email">Email</Label>
|
|
||||||
<Input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="password">Пароль</Label>
|
|
||||||
<Input
|
|
||||||
type="password"
|
|
||||||
id="password"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<Button type="submit" className="w-full">
|
|
||||||
Войти
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Binary file not shown.
438
frontend/style/app/main.go
Normal file
438
frontend/style/app/main.go
Normal file
@@ -0,0 +1,438 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/gorilla/handlers"
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var db *sql.DB
|
||||||
|
|
||||||
|
func create_table(command string) {
|
||||||
|
_, err := db.Exec(command)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Ошибка при создании таблицы:", err)
|
||||||
|
}
|
||||||
|
fmt.Println("База данных готова к работе.")
|
||||||
|
}
|
||||||
|
|
||||||
|
func initDB() {
|
||||||
|
var err error
|
||||||
|
dbFile := "UNITED.db"
|
||||||
|
db, err = sql.Open("sqlite3", dbFile)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Ошибка подключения к базе данных:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create tables if they don't exist
|
||||||
|
create_table(`
|
||||||
|
CREATE TABLE IF NOT EXISTS pay_urls (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
url TEXT NOT NULL
|
||||||
|
);`)
|
||||||
|
|
||||||
|
create_table(`
|
||||||
|
CREATE TABLE IF NOT EXISTS order_list (
|
||||||
|
order_id TEXT PRIMARY KEY,
|
||||||
|
total_price REAL NOT NULL,
|
||||||
|
datetime TEXT NOT NULL
|
||||||
|
);`)
|
||||||
|
|
||||||
|
create_table(`CREATE TABLE IF NOT EXISTS order_lines (
|
||||||
|
line_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
order_id TEXT NOT NULL,
|
||||||
|
item_id INTEGER NOT NULL,
|
||||||
|
item_title TEXT NOT NULL,
|
||||||
|
item_price REAL NOT NULL,
|
||||||
|
item_quantity INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (order_id) REFERENCES order_list(order_id)
|
||||||
|
);`)
|
||||||
|
|
||||||
|
create_table(`CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
password TEXT NOT NULL
|
||||||
|
);`)
|
||||||
|
|
||||||
|
fmt.Println("База данных готова к работе.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/*----------------------------PAYMENT--------------------------------------*/
|
||||||
|
func payHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
// Структура для тела запроса на localhost:5000
|
||||||
|
type PaymentRequest struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Sum float64 `json:"sum"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Структура для ответа от localhost:5000
|
||||||
|
type PaymentResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
URL string `json:"redir_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
cookie, err := r.Cookie("totalPrice")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Не удалось получить amount из cookies", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Преобразуем amount из строки в float64
|
||||||
|
amount, err := strconv.ParseFloat(cookie.Value, 64)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Некорректное значение amount в cookies", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Генерируем новый UUID
|
||||||
|
newUUID := uuid.New().String()
|
||||||
|
|
||||||
|
// Создаем тело запроса для localhost:5000
|
||||||
|
paymentRequest := PaymentRequest{
|
||||||
|
ID: newUUID,
|
||||||
|
Sum: amount,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Преобразуем тело запроса в JSON
|
||||||
|
requestBody, err := json.Marshal(paymentRequest)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при создании запроса", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отправляем POST-запрос на localhost:5000
|
||||||
|
resp, err := http.Post("http://localhost:5000/pay", "application/json", bytes.NewBuffer(requestBody))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при отправке запроса на сервер", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
// Читаем ответ от сервера
|
||||||
|
var paymentResponse PaymentResponse
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&paymentResponse); err != nil {
|
||||||
|
http.Error(w, "Ошибка при чтении ответа от сервера", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сохраняем данные в базу данных
|
||||||
|
insertSQL := `INSERT INTO pay_urls (uuid, url) VALUES (?, ?)`
|
||||||
|
_, err = db.Exec(insertSQL, newUUID, paymentResponse.URL)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Формируем ответ клиенту в виде простого текста
|
||||||
|
response := fmt.Sprintf("UUID: %s\nURL: %s", newUUID, paymentResponse.URL)
|
||||||
|
|
||||||
|
// Set uuid cookie
|
||||||
|
cookie = &http.Cookie{
|
||||||
|
Name: "uuid",
|
||||||
|
Value: newUUID,
|
||||||
|
Expires: time.Now().Add(30 * time.Minute),
|
||||||
|
}
|
||||||
|
http.SetCookie(w, cookie)
|
||||||
|
// Отправляем ответ в виде простого текста
|
||||||
|
w.Header().Set("Content-Type", "text/plain")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
w.Write([]byte(response))
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkPayHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Извлекаем uuid из cookie
|
||||||
|
cookie, err := r.Cookie("uuid")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Не найден cookie с uuid", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uuid := cookie.Value
|
||||||
|
if uuid == "" {
|
||||||
|
http.Error(w, "Пустое значение uuid", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем существование uuid в базе данных
|
||||||
|
var exists bool
|
||||||
|
querySQL := `SELECT EXISTS(SELECT 1 FROM pay_urls WHERE uuid = ?)`
|
||||||
|
err = db.QueryRow(querySQL, uuid).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при проверке uuid в базе данных", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !exists {
|
||||||
|
http.Error(w, "UUID не найден", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Создаем тело запроса для localhost:5000/check_pay
|
||||||
|
checkRequest := struct {
|
||||||
|
UUID string `json:"uuid"`
|
||||||
|
}{
|
||||||
|
UUID: uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
requestBody, err := json.Marshal(checkRequest)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при создании запроса", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отправляем POST-запрос на localhost:5000/check_pay
|
||||||
|
resp, err := http.Post("http://localhost:5000/check_pay", "application/json", bytes.NewBuffer(requestBody))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при отправке запроса на сервер", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
// Читаем ответ от сервера
|
||||||
|
var checkResponse struct {
|
||||||
|
Mes string `json:"mes"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&checkResponse); err != nil {
|
||||||
|
http.Error(w, "Ошибка при чтении ответа от сервера", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Формируем ответ клиенту в зависимости от полученного результата
|
||||||
|
var response string
|
||||||
|
if checkResponse.Mes == "OK" {
|
||||||
|
response = "OK"
|
||||||
|
} else {
|
||||||
|
response = "GTHO"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Отправляем ответ в виде простого текста
|
||||||
|
w.Header().Set("Content-Type", "text/plain")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
w.Write([]byte(response))
|
||||||
|
}
|
||||||
|
|
||||||
|
func add_to_cart(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
cartCookie, err := r.Cookie("cart")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Cart cookie not found", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Print("cartCookie.Value: ", cartCookie.Value)
|
||||||
|
cartValue := strings.ReplaceAll(cartCookie.Value, "'", "\"") // Replace single quotes with double quotes
|
||||||
|
var cart Cart
|
||||||
|
|
||||||
|
err = json.Unmarshal([]byte(cartValue), &cart)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Invalid cart data format", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, item := range cart.CartItems {
|
||||||
|
fmt.Println("Item ID:", item.ID)
|
||||||
|
fmt.Println("Item Title:", item.Title)
|
||||||
|
fmt.Println("Item Price:", item.Price)
|
||||||
|
fmt.Println("Item Quantity:", item.Quantity)
|
||||||
|
}
|
||||||
|
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
|
||||||
|
fmt.Println("order_id: ", order_id)
|
||||||
|
fmt.Println("total_price: ", total_price)
|
||||||
|
|
||||||
|
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, "Ошибка при сохранении данных в базу данных 1", http.StatusInternalServerError)
|
||||||
|
fmt.Print("Ошибка при сохранении данных в базу данных 1", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range cart.CartItems {
|
||||||
|
|
||||||
|
insertSQL := `INSERT INTO order_lines (order_id, item_id, item_title, item_price, item_quantity) VALUES (?, ?, ?, ?, ?)`
|
||||||
|
_, err = db.Exec(insertSQL, order_id, item.ID, item.Title, item.Price, item.Quantity)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка при сохранении данных в базу данных 2", http.StatusInternalServerError)
|
||||||
|
fmt.Println("Ошибка при сохранении данных в базу данных 2", err)
|
||||||
|
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"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/*----------------------------USER-----------------------------------------*/
|
||||||
|
func registerHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
log.Printf("Received request with method: %s", r.Method)
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var user User
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
|
||||||
|
http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.Email == "" || user.Password == "" {
|
||||||
|
http.Error(w, "Email и пароль обязательны", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
insertQuery := `INSERT INTO users (email, password) VALUES (?, ?)`
|
||||||
|
_, err := db.Exec(insertQuery, user.Email, user.Password)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка записи в базу данных", http.StatusInternalServerError)
|
||||||
|
fmt.Println("Ошибка:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"message": "Пользователь успешно зарегистрирован", "email": user.Email})
|
||||||
|
}
|
||||||
|
|
||||||
|
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
log.Printf("Received request with method: %s", r.Method)
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var user User
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
|
||||||
|
http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.Email == "" || user.Password == "" {
|
||||||
|
http.Error(w, "Email и пароль обязательны", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
query := `SELECT id, email, password FROM users WHERE email = ? AND password = ?`
|
||||||
|
var dbUser User
|
||||||
|
err := db.QueryRow(query, user.Email, user.Password).Scan(&dbUser.ID, &dbUser.Email, &dbUser.Password)
|
||||||
|
if err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
http.Error(w, "Неверные учетные данные", http.StatusUnauthorized)
|
||||||
|
} else {
|
||||||
|
http.Error(w, "Ошибка при проверке учетных данных", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"message": "Вход успешен", "email": dbUser.Email})
|
||||||
|
}
|
||||||
|
|
||||||
|
func getUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
log.Printf("Received request with method: %s", r.Method)
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := db.Query(`SELECT id, email, password FROM users`)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Ошибка чтения из базы данных", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var users []User
|
||||||
|
for rows.Next() {
|
||||||
|
var user User
|
||||||
|
if err := rows.Scan(&user.ID, &user.Email, &user.Password); err != nil {
|
||||||
|
http.Error(w, "Ошибка обработки данных", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
users = append(users, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(users)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
|
||||||
|
initDB()
|
||||||
|
defer db.Close()
|
||||||
|
// Setup CORS
|
||||||
|
cors := handlers.CORS(
|
||||||
|
handlers.AllowedOrigins([]string{"*"}),
|
||||||
|
handlers.AllowedMethods([]string{"GET", "POST"}),
|
||||||
|
handlers.AllowedHeaders([]string{"Content-Type"}),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Register handlers
|
||||||
|
http.HandleFunc("/api/pay", payHandler)
|
||||||
|
http.HandleFunc("/api/check_pay", checkPayHandler)
|
||||||
|
http.HandleFunc("/api/add_to_cart", add_to_cart)
|
||||||
|
http.HandleFunc("/api/register", registerHandler)
|
||||||
|
http.HandleFunc("/api/login", loginHandler)
|
||||||
|
http.HandleFunc("/api/users", getUsersHandler)
|
||||||
|
|
||||||
|
// Start server with CORS middleware
|
||||||
|
port := os.Getenv("PORT")
|
||||||
|
if port == "" {
|
||||||
|
port = "8081"
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Go-сервер запущен на порту", port)
|
||||||
|
log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux)))
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ export default function AccountPage() {
|
|||||||
const handleLogin = async (e: React.FormEvent) => {
|
const handleLogin = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
try {
|
try {
|
||||||
const response = await fetch("http://localhost:8080/api/login", {
|
const response = await fetch("http://localhost:8081/api/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -50,7 +50,7 @@ export default function AccountPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const response = await fetch("http://localhost:8080/api/register", {
|
const response = await fetch("http://localhost:8081/api/register", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
|||||||
@@ -1,160 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"database/sql"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/gorilla/handlers"
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID int `json:"id"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var db *sql.DB
|
|
||||||
|
|
||||||
func initDB() {
|
|
||||||
var err error
|
|
||||||
dbFile := "users.db"
|
|
||||||
db, err = sql.Open("sqlite3", dbFile)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Ошибка подключения к базе данных:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
createTableQuery := `
|
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
password TEXT NOT NULL
|
|
||||||
);`
|
|
||||||
_, err = db.Exec(createTableQuery)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Ошибка при создании таблицы:", err)
|
|
||||||
}
|
|
||||||
fmt.Println("База данных готова к работе.")
|
|
||||||
}
|
|
||||||
|
|
||||||
func registerHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("Received request with method: %s", r.Method)
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var user User
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
|
|
||||||
http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if user.Email == "" || user.Password == "" {
|
|
||||||
http.Error(w, "Email и пароль обязательны", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
insertQuery := `INSERT INTO users (email, password) VALUES (?, ?)`
|
|
||||||
_, err := db.Exec(insertQuery, user.Email, user.Password)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Ошибка записи в базу данных", http.StatusInternalServerError)
|
|
||||||
fmt.Println("Ошибка:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"message": "Пользователь успешно зарегистрирован", "email": user.Email})
|
|
||||||
}
|
|
||||||
|
|
||||||
func loginHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("Received request with method: %s", r.Method)
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var user User
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
|
|
||||||
http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if user.Email == "" || user.Password == "" {
|
|
||||||
http.Error(w, "Email и пароль обязательны", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
query := `SELECT id, email, password FROM users WHERE email = ? AND password = ?`
|
|
||||||
var dbUser User
|
|
||||||
err := db.QueryRow(query, user.Email, user.Password).Scan(&dbUser.ID, &dbUser.Email, &dbUser.Password)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
http.Error(w, "Неверные учетные данные", http.StatusUnauthorized)
|
|
||||||
} else {
|
|
||||||
http.Error(w, "Ошибка при проверке учетных данных", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"message": "Вход успешен", "email": dbUser.Email})
|
|
||||||
}
|
|
||||||
|
|
||||||
func getUsersHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("Received request with method: %s", r.Method)
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
rows, err := db.Query(`SELECT id, email, password FROM users`)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Ошибка чтения из базы данных", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var users []User
|
|
||||||
for rows.Next() {
|
|
||||||
var user User
|
|
||||||
if err := rows.Scan(&user.ID, &user.Email, &user.Password); err != nil {
|
|
||||||
http.Error(w, "Ошибка обработки данных", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
users = append(users, user)
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(users)
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
initDB()
|
|
||||||
defer db.Close()
|
|
||||||
|
|
||||||
// Setup CORS
|
|
||||||
cors := handlers.CORS(
|
|
||||||
handlers.AllowedOrigins([]string{"*"}),
|
|
||||||
handlers.AllowedMethods([]string{"GET", "POST"}),
|
|
||||||
handlers.AllowedHeaders([]string{"Content-Type"}),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Register handlers
|
|
||||||
http.HandleFunc("/api/register", registerHandler)
|
|
||||||
http.HandleFunc("/api/login", loginHandler)
|
|
||||||
http.HandleFunc("/api/users", getUsersHandler)
|
|
||||||
|
|
||||||
// Start server with CORS middleware
|
|
||||||
port := os.Getenv("PORT")
|
|
||||||
if port == "" {
|
|
||||||
port = "8080"
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("Go-сервер запущен на порту", port)
|
|
||||||
log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux)))
|
|
||||||
}
|
|
||||||
Binary file not shown.
@@ -1,78 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
|
|
||||||
export default function RegisterPage() {
|
|
||||||
const [email, setEmail] = useState("");
|
|
||||||
const [password, setPassword] = useState("");
|
|
||||||
const [confirmPassword, setConfirmPassword] = useState("");
|
|
||||||
const [message, setMessage] = useState("");
|
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
|
|
||||||
if (password !== confirmPassword) {
|
|
||||||
setMessage("Пароли не совпадают");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch("http://localhost:8080/api/register", {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ email, password }),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
setMessage("Регистрация прошла успешно!");
|
|
||||||
} else {
|
|
||||||
const errorText = await response.text();
|
|
||||||
setMessage(`Ошибка при регистрации: ${errorText}`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Ошибка сети:", error);
|
|
||||||
setMessage("Ошибка сети");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="container mx-auto px-4 py-8">
|
|
||||||
<h1 className="text-2xl font-bold mb-6">Регистрация</h1>
|
|
||||||
<form onSubmit={handleSubmit}>
|
|
||||||
<div>
|
|
||||||
<label>Email:</label>
|
|
||||||
<input
|
|
||||||
type="email"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
className="border rounded w-full p-2 mb-4"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Пароль:</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
className="border rounded w-full p-2 mb-4"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Подтвердите пароль:</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={confirmPassword}
|
|
||||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
|
||||||
className="border rounded w-full p-2 mb-4"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<button type="submit" className="bg-black text-white py-2 px-4 rounded">
|
|
||||||
Зарегистрироваться
|
|
||||||
</button>
|
|
||||||
{message && <p className="mt-4 text-red-500">{message}</p>}
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"database/sql"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/gorilla/handlers"
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID int `json:"id"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var db *sql.DB
|
|
||||||
|
|
||||||
func initDB() {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
dbFile := "users.db"
|
|
||||||
db, err = sql.Open("sqlite3", dbFile)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Ошибка подключения к базе данных:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
createTableQuery := `
|
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
password TEXT NOT NULL
|
|
||||||
);`
|
|
||||||
_, err = db.Exec(createTableQuery)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Ошибка при создании таблицы:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("База данных готова к работе.")
|
|
||||||
}
|
|
||||||
|
|
||||||
func registerHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("Received request with method: %s", r.Method)
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var user User
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
|
|
||||||
http.Error(w, "Ошибка обработки JSON", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if user.Email == "" || user.Password == "" {
|
|
||||||
http.Error(w, "Все поля обязательны для заполнения", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
insertQuery := `INSERT INTO users (email, password) VALUES (?, ?)`
|
|
||||||
_, err := db.Exec(insertQuery, user.Email, user.Password)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Ошибка записи в базу данных", http.StatusInternalServerError)
|
|
||||||
fmt.Println("Ошибка:", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
w.Write([]byte("Пользователь успешно зарегистрирован"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func getUsersHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Printf("Received request with method: %s", r.Method)
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
http.Error(w, "Метод не поддерживается", http.StatusMethodNotAllowed)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
rows, err := db.Query(`SELECT id, email, password FROM users`)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Ошибка чтения из базы данных", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var users []User
|
|
||||||
for rows.Next() {
|
|
||||||
var user User
|
|
||||||
if err := rows.Scan(&user.ID, &user.Email, &user.Password); err != nil {
|
|
||||||
http.Error(w, "Ошибка обработки данных", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
users = append(users, user)
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(users)
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
initDB()
|
|
||||||
defer db.Close()
|
|
||||||
|
|
||||||
// Setup CORS
|
|
||||||
cors := handlers.CORS(
|
|
||||||
handlers.AllowedOrigins([]string{"*"}),
|
|
||||||
handlers.AllowedMethods([]string{"GET", "POST"}),
|
|
||||||
handlers.AllowedHeaders([]string{"Content-Type"}),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Register handlers
|
|
||||||
http.HandleFunc("/api/register", registerHandler)
|
|
||||||
http.HandleFunc("/api/users", getUsersHandler)
|
|
||||||
|
|
||||||
// Start server with CORS middleware
|
|
||||||
port := os.Getenv("PORT")
|
|
||||||
if port == "" {
|
|
||||||
port = "8080"
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Println("Go-сервер запущен на порту", port)
|
|
||||||
log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux)))
|
|
||||||
}
|
|
||||||
Binary file not shown.
@@ -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');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
28
go.mod
28
go.mod
@@ -3,30 +3,16 @@ module market
|
|||||||
go 1.18
|
go 1.18
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/gorilla/handlers v1.5.2
|
||||||
|
github.com/gorilla/mux v1.8.1
|
||||||
github.com/jmoiron/sqlx v1.4.0
|
github.com/jmoiron/sqlx v1.4.0
|
||||||
|
github.com/joho/godotenv v1.5.1
|
||||||
github.com/lib/pq v1.10.9
|
github.com/lib/pq v1.10.9
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.24
|
||||||
|
github.com/rs/cors v1.11.1
|
||||||
gopkg.in/yaml.v2 v2.4.0
|
gopkg.in/yaml.v2 v2.4.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require github.com/felixge/httpsnoop v1.0.3 // indirect
|
||||||
github.com/felixge/httpsnoop v1.0.3 // indirect
|
|
||||||
github.com/gorilla/handlers v1.5.2 // indirect
|
|
||||||
github.com/gorilla/mux v1.8.1 // indirect
|
|
||||||
github.com/joho/godotenv v1.5.1 // indirect
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
require github.com/google/uuid v1.6.0
|
||||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
|
||||||
github.com/gofiber/fiber/v2 v2.52.6 // indirect
|
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
|
||||||
github.com/klauspost/compress v1.17.9 // indirect
|
|
||||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
|
||||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
|
||||||
github.com/rivo/uniseg v0.2.0 // indirect
|
|
||||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
|
||||||
github.com/valyala/fasthttp v1.51.0 // indirect
|
|
||||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
|
||||||
golang.org/x/crypto v0.32.0
|
|
||||||
golang.org/x/sys v0.29.0 // indirect
|
|
||||||
)
|
|
||||||
|
|||||||
34
go.sum
34
go.sum
@@ -1,55 +1,27 @@
|
|||||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
|
||||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
|
||||||
github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=
|
github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=
|
||||||
github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||||
github.com/gofiber/fiber/v2 v2.52.6 h1:Rfp+ILPiYSvvVuIPvxrBns+HJp8qGLDnLJawAu27XVI=
|
|
||||||
github.com/gofiber/fiber/v2 v2.52.6/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
|
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
|
github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
|
||||||
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
|
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
|
||||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
|
||||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
|
||||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
|
|
||||||
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
|
||||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
|
||||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
|
||||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
|
||||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
|
||||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
|
||||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
|
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
|
||||||
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
|
||||||
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
|
|
||||||
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
|
|
||||||
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
|
||||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
|
||||||
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
|
|
||||||
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
|
|
||||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
|
||||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|
||||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
|
||||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
package products
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
package products
|
|
||||||
|
|
||||||
type Product struct {
|
|
||||||
ID int `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
Price float64 `json:"price"`
|
|
||||||
Stock int `json:"stock"`
|
|
||||||
Images []string `json:"images"`
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
package products
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
package products
|
|
||||||
|
|
||||||
// Product - структура для товара
|
|
||||||
type Product struct {
|
|
||||||
Name string
|
|
||||||
Price float64
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProductService - сервис для работы с товарами
|
|
||||||
type ProductService struct {
|
|
||||||
products []Product
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewProductService - создание нового экземпляра ProductService
|
|
||||||
func NewProductService() *ProductService {
|
|
||||||
return &ProductService{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddProduct - добавление товара в сервис
|
|
||||||
func (s *ProductService) AddProduct(product Product) {
|
|
||||||
s.products = append(s.products, product)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAllProducts - получение списка всех товаров
|
|
||||||
func (s *ProductService) GetAllProducts() []Product {
|
|
||||||
return s.products
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
db "market/database"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Data структура для входящих данных
|
|
||||||
type Data struct {
|
|
||||||
ID int `json:"ID"`
|
|
||||||
Count int `json:"Count"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Account struct {
|
|
||||||
Login string `json:"Login"`
|
|
||||||
Password string `json:"Password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func HashPassword(password string) (string) {
|
|
||||||
// Генерация хэша с заданным уровнем сложности (по умолчанию 10)
|
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return string(hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckPassword сравнивает хэшированный пароль с обычным
|
|
||||||
func CheckPassword(hashedPassword, plainPassword string) bool {
|
|
||||||
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(plainPassword))
|
|
||||||
return err == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// Инициализация Fiber
|
|
||||||
app := fiber.New()
|
|
||||||
|
|
||||||
// Маршрут для обработки POST-запроса
|
|
||||||
app.Post("/register", func(c *fiber.Ctx) error {
|
|
||||||
// var input []Data
|
|
||||||
var input Account
|
|
||||||
// Парсинг входящих данных
|
|
||||||
if err := c.BodyParser(&input); err != nil {
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
|
||||||
"message": "err",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
check_auth := fmt.Sprintf("SELECT ID, login WHERE login=%s", input.Login)
|
|
||||||
is_exist := db.Insert_Data(check_auth)
|
|
||||||
if is_exist{
|
|
||||||
pswd := HashPassword(input.Password)
|
|
||||||
formatted := fmt.Sprintf("INSERT INTO users (login, hash_password) VALUES (%s, %s)", input.Login, pswd)
|
|
||||||
err := db.Insert_Data(formatted)
|
|
||||||
if err == false {
|
|
||||||
log.Printf("Ошибка при вставке данных")
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
|
||||||
"message": "err",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
|
||||||
"message": "OK",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
// Запуск сервера
|
|
||||||
log.Fatal(app.Listen(":3000"))
|
|
||||||
}
|
|
||||||
18
|
|
||||||
Binary file not shown.
@@ -1,55 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Pay(sum float64) string{
|
|
||||||
// Базовый URL
|
|
||||||
baseURL := "https://yoomoney.ru/quickpay/confirm.xml"
|
|
||||||
baseSum := fmt.Sprintf("%f", sum)
|
|
||||||
|
|
||||||
// Параметры запроса
|
|
||||||
params := url.Values{}
|
|
||||||
params.Add("receiver", "410012845407838")
|
|
||||||
params.Add("quickpay-form", "shop")
|
|
||||||
params.Add("targets", "Тестовая покупка")
|
|
||||||
params.Add("paymentType", "SB")
|
|
||||||
params.Add("sum", baseSum)
|
|
||||||
params.Add("label", "cheche")
|
|
||||||
|
|
||||||
// Формируем полный URL с параметрами
|
|
||||||
fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
|
|
||||||
// fmt.Println("Request URL:", fullURL)
|
|
||||||
|
|
||||||
// Создаем кастомный HTTP-клиент с отключенными редиректами
|
|
||||||
client := &http.Client{
|
|
||||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
|
||||||
// Останавливаемся после первого редиректа
|
|
||||||
return http.ErrUseLastResponse
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Отправляем POST-запрос с пустым телом
|
|
||||||
resp, err := client.Post(fullURL, "application/x-www-form-urlencoded", nil)
|
|
||||||
if err != nil {
|
|
||||||
// fmt.Println("Error sending request:", err)
|
|
||||||
return "WHOOPS"
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
location, err := resp.Location()
|
|
||||||
if err != nil {
|
|
||||||
// fmt.Println("Error getting location:", err)
|
|
||||||
return "WHOOPS"
|
|
||||||
}
|
|
||||||
// fmt.Println("Redirect URL:", location.String())
|
|
||||||
return location.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
pay := Pay(6.0)
|
|
||||||
fmt.Println(pay)
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user