modified: main.go

add getUser hander
This commit is contained in:
2025-09-25 16:15:41 +05:00
parent 0430c0f29f
commit 56a236870e
+22
View File
@@ -21,6 +21,23 @@ type User struct {
Email string Email string
} }
func getUser(w http.ResponseWriter, r *http.Request) {
db, ok := r.Context().Value("db").(*gorm.DB)
if !ok {
http.Error(w, "Database connection not found", http.StatusInternalServerError)
return
}
var user User
if err := db.First(&user).Error; err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
func handler(w http.ResponseWriter, r *http.Request) { func handler(w http.ResponseWriter, r *http.Request) {
// Get DB connection from context // Get DB connection from context
db, ok := r.Context().Value("db").(*gorm.DB) db, ok := r.Context().Value("db").(*gorm.DB)
@@ -56,6 +73,11 @@ func main() {
handler(w, r) handler(w, r)
}) })
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), "db", db))
getUser(w, r)
})
log.Println("Сервер запущен на http://localhost:8080") log.Println("Сервер запущен на http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil)) log.Fatal(http.ListenAndServe(":8080", nil))
} }