Refactoring

This commit is contained in:
2025-02-20 12:50:08 +01:00
parent 9e037a9c25
commit 47caa3a8a2
16 changed files with 4 additions and 524 deletions

View File

@@ -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)))
}

View File

@@ -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.

View File

@@ -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",

View File

@@ -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>
);
}

View File

@@ -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.