Files
tp/serv_golang_rest_api/main.go
T
valitovgaziz 56a236870e modified: main.go
add getUser hander
2025-09-25 16:15:41 +05:00

83 lines
1.9 KiB
Go

package main
import (
"context"
"encoding/json"
"log"
"net/http"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Response struct {
Message string `json:"message"`
}
// Example model
type User struct {
gorm.Model
Name 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) {
// Get DB connection from context
db, ok := r.Context().Value("db").(*gorm.DB)
if !ok {
http.Error(w, "Database connection not found", http.StatusInternalServerError)
return
}
// Example usage
db.AutoMigrate(&User{})
user := User{Name: "Test", Email: "test@example.com"}
db.Create(&user)
w.Header().Set("Content-Type", "application/json")
response := Response{Message: "ok"}
json.NewEncoder(w).Encode(response)
}
func main() {
// Create DB connection string
dsn := "host=db user=postgres password=postgres dbname=mydb port=5432 sslmode=disable TimeZone=UTC"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
// Initialize database
db.AutoMigrate(&User{})
// Setup HTTP server with DB context
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), "db", db))
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))
}