Compare commits
4 Commits
1e803b4beb
...
9e037a9c25
| Author | SHA1 | Date | |
|---|---|---|---|
| 9e037a9c25 | |||
| 19b8f0716b | |||
| 09b545bf47 | |||
| 964f1411da |
218
frontend/style/app/pay/pay.go
Normal file
218
frontend/style/app/pay/pay.go
Normal file
@@ -0,0 +1,218 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/handlers"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
// Структура для тела запроса на 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"`
|
||||
}
|
||||
|
||||
var db *sql.DB
|
||||
|
||||
func initDB() {
|
||||
var err error
|
||||
dbFile := "urls_pay.db"
|
||||
db, err = sql.Open("sqlite3", dbFile)
|
||||
if err != nil {
|
||||
log.Fatal("Ошибка подключения к базе данных:", err)
|
||||
}
|
||||
|
||||
// Создаем таблицу pay_urls, если она не существует
|
||||
createTableSQL := `
|
||||
CREATE TABLE IF NOT EXISTS pay_urls (
|
||||
id TEXT PRIMARY KEY,
|
||||
url TEXT NOT NULL
|
||||
);`
|
||||
_, err = db.Exec(createTableSQL)
|
||||
if err != nil {
|
||||
log.Fatal("Ошибка при создании таблицы pay_urls:", err)
|
||||
}
|
||||
|
||||
fmt.Println("База данных готова к работе.")
|
||||
}
|
||||
|
||||
func payHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
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 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)
|
||||
|
||||
// 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)))
|
||||
}
|
||||
BIN
frontend/style/app/pay/urls_pay.db
Normal file
BIN
frontend/style/app/pay/urls_pay.db
Normal file
Binary file not shown.
16
go.mod
16
go.mod
@@ -3,22 +3,22 @@ module market
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
github.com/gorilla/handlers v1.5.2
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/jmoiron/sqlx v1.4.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/lib/pq v1.10.9
|
||||
github.com/mattn/go-sqlite3 v1.14.22
|
||||
github.com/rs/cors v1.11.1
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
)
|
||||
|
||||
require (
|
||||
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 github.com/felixge/httpsnoop v1.0.3 // indirect
|
||||
|
||||
require (
|
||||
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/gofiber/fiber/v2 v2.52.6
|
||||
github.com/google/uuid v1.6.0
|
||||
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
|
||||
|
||||
10
go.sum
10
go.sum
@@ -12,8 +12,6 @@ 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/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
|
||||
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/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
@@ -31,11 +29,12 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
|
||||
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 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
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/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
|
||||
@@ -46,10 +45,9 @@ 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 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
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/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
|
||||
Reference in New Issue
Block a user