f7b09e260c
modified: go.sum modified: internal/handlers/auth.go new file: internal/handlers/oauth.go modified: internal/handlers/user_handler.go renamed: internal/model/o_auth_provider.go -> internal/models/o_auth_provider.go renamed: internal/model/user.go -> internal/models/user.go modified: internal/repository/user_repository.go modified: internal/service/user_service.go modified: pkg/database/postgres.go add oauth_handler
66 lines
1.7 KiB
Go
66 lines
1.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"serv_golang_rest_api/internal/models"
|
|
"serv_golang_rest_api/internal/service"
|
|
)
|
|
|
|
type UserHandler struct {
|
|
userService *service.UserService
|
|
}
|
|
|
|
func NewUserHandler(userService *service.UserService) *UserHandler {
|
|
return &UserHandler{userService: userService}
|
|
}
|
|
|
|
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
|
var req models.CreateUserRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
user, err := h.userService.CreateUser(&req)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
json.NewEncoder(w).Encode(user)
|
|
}
|
|
|
|
func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
|
|
idStr := chi.URLParam(r, "id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
http.Error(w, "Invalid user ID", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
user, err := h.userService.GetUserByID(uint(id))
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(user)
|
|
}
|
|
|
|
func (h *UserHandler) GetAllUsers(w http.ResponseWriter, r *http.Request) {
|
|
users, err := h.userService.GetAllUsers()
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(users)
|
|
} |