7987472635
modified: main_dc/yalarba/api_yal/internal/domain/auth/router.go modified: main_dc/yalarba/api_yal/internal/domain/auth/servcie.go set mock service for auth layer
56 lines
1.4 KiB
Go
56 lines
1.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
// AuthHandler обработчик для аутентификации
|
|
type AuthHandler struct {
|
|
authService AuthService
|
|
validator *validator.Validate
|
|
}
|
|
|
|
// NewAuthHandler создает новый экземпляр AuthHandler
|
|
func NewAuthHandler(authService *AuthService) *AuthHandler {
|
|
return &AuthHandler{
|
|
authService: *NewAuthService(),
|
|
validator: validator.New(),
|
|
}
|
|
}
|
|
|
|
// Register регистрация аккаунта пользователя
|
|
func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var req RegisterRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := h.validator.Struct(req); err != nil {
|
|
var invalidValidationError *validator.InvalidValidationError
|
|
if errors.As(err, &invalidValidationError) {
|
|
http.Error(w, "Invalid request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var errs []string
|
|
for _, err := range err.(validator.ValidationErrors) {
|
|
errs = append(errs, fmt.Sprintf("field %s is invalid: %s", err.Field(), err.Tag()))
|
|
}
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"error": "Validation failed",
|
|
"fields": errs,
|
|
})
|
|
return
|
|
}
|
|
|
|
}
|