package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
_ "github.com/denisenkom/go-mssqldb"
)
var db *sql.DB
func main() {
// Get the DB_URI from environment variables
dbURI := os.Getenv("DB_URI")
if dbURI == "" {
log.Fatal("DB_URI environment variable is not set")
}
// Open the database connection with the MSSQL URI
var err error
db, err = sql.Open("sqlserver", dbURI)
if err != nil {
log.Fatalf("Failed to open database connection: %v", err)
}
// Set connection pool parameters
db.SetMaxOpenConns(10) // Maximum number of open connections
db.SetMaxIdleConns(5) // Maximum number of idle connections
db.SetConnMaxIdleTime(0) // No timeout for idle connections
// Verify connection
if err := db.Ping(); err != nil {
log.Fatalf("Failed to ping database: %v", err)
}
log.Println("Connected to database successfully!")
// Set up HTTP server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if err := db.Ping(); err != nil {
fmt.Fprintf(w, "Database connection failed: %v", err)
} else {
fmt.Fprintln(w, "Database connection successful!")
}
})
log.Println("Server is running on http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("HTTP server failed: %v", err)
}
}