diff --git a/serv_golang_rest_api/main.go b/serv_golang_rest_api/main.go index b324778..9250efa 100644 --- a/serv_golang_rest_api/main.go +++ b/serv_golang_rest_api/main.go @@ -21,6 +21,23 @@ type User struct { 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) { // Get DB connection from context db, ok := r.Context().Value("db").(*gorm.DB) @@ -56,6 +73,11 @@ func main() { 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.Fatal(http.ListenAndServe(":8080", nil)) } \ No newline at end of file