add go gorm chi postgres starter

This commit is contained in:
2024-06-13 02:06:01 +02:00
parent 0895bb8cfd
commit cfe65135d8
6 changed files with 130 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
package main
import (
"context"
"go-postgres-gorm-chi-starter/model"
"log"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func main() {
// Get the database connection
dsn := "host=localhost user=golang password=golang dbname=golang port=5432 sslmode=disable TimeZone=Europe/Belgrade"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("Error connecting to the database: %v", err)
}
// Migrations
db.AutoMigrate(&model.User{})
router := chi.NewRouter()
// Middleware
router.Use(middleware.RequestID)
router.Use(middleware.RealIP)
router.Use(middleware.Logger)
router.Use(middleware.Recoverer)
router.Use(middleware.Timeout(60 * time.Second))
router.Use(ApiCtx(db))
// Routes
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
// Extract the database connection from the context
ctx := r.Context()
db := ctx.Value("db").(*gorm.DB)
// Send the database name as a response
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(db.Name()))
})
// Start server
log.Println("Starting server on :8080")
http.ListenAndServe(":8080", router)
}
func ApiCtx(db *gorm.DB) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "db", db)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}