Refactoring
This commit is contained in:
@@ -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.
@@ -21,7 +21,7 @@ export default function AccountPage() {
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
try {
|
||||
const response = await fetch("http://localhost:8080/api/login", {
|
||||
const response = await fetch("http://localhost:8081/api/login", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -50,7 +50,7 @@ export default function AccountPage() {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch("http://localhost:8080/api/register", {
|
||||
const response = await fetch("http://localhost:8081/api/register", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
||||
@@ -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.
2
go.mod
2
go.mod
@@ -23,7 +23,9 @@ require (
|
||||
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/mattn/go-sqlite3 v1.14.24
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/rs/cors v1.11.1
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.51.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
|
||||
@@ -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