pocketbase-signer/handlers/register.go

91 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handlers
import (
"fmt"
"log"
"net/http"
"pocketbaseSigner/models"
"bytes"
"encoding/json"
)
func RegisterFormHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
http.ServeFile(w, r, "./web/register_form.html")
return
}
if r.Method == http.MethodPost {
err := r.ParseForm()
if err != nil {
http.Error(w, "Ошибка при обработке формы", http.StatusBadRequest)
return
}
user := models.UserForm{
Email: r.FormValue("email"),
Password: r.FormValue("password"),
PasswordConfirm: r.FormValue("password_confirm"),
FirstName: r.FormValue("firstname"),
LastName: r.FormValue("lastname"),
Phone: r.FormValue("phone"),
}
// нужно для маршалинга потому что переменные с маленькой буквы потеряются
// если все переменные делать с большой буквы, то pocketbase не примет
dataMap := map[string]string{
"email": user.Email,
"password": user.Password,
"passwordConfirm": user.PasswordConfirm,
"FirstName": user.FirstName,
"LastName": user.LastName,
"Phone": user.Phone,
}
data, err := json.Marshal(dataMap)
if r.FormValue("password") != r.FormValue("password_confirm") {
http.Error(w, "Пароли не совпали", http.StatusBadRequest)
return
}
// Проверка
if user.Email == "" || user.Password == "" {
http.Error(w, "Email и пароль обязательны!", http.StatusBadRequest)
return
}
log.Printf("Получен пользователь: %+v\n", user)
fmt.Println(json.Marshal(user))
fmt.Println()
if err != nil {
fmt.Println(err)
return
}
url:= "http://localhost:8090/api/collections/users/records"
fmt.Println(bytes.NewBuffer(data))
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bytes.NewBuffer(data))
fmt.Println()
req.Header.Set("Content-Type", "application/json")
fmt.Println(req)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
http.Error(w, "Данные отправлены", http.StatusOK)
}
}