2c07fba277
modified: go.mod modified: go.sum modified: main.go add db for rest api
60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"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 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)
|
|
})
|
|
|
|
log.Println("Сервер запущен на http://localhost:8080")
|
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
|
} |