modified: main.go
add getUser hander
This commit is contained in:
@@ -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))
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user