-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
executable file
·77 lines (62 loc) · 1.77 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
var db *sql.DB
func main() {
// Load environment variables from .env file
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env file")
}
// Retrieve PostgreSQL connection details from environment variables
host := os.Getenv("POSTGRES_HOST")
port := os.Getenv("POSTGRES_PORT")
user := os.Getenv("POSTGRES_USER")
password := os.Getenv("POSTGRES_DBPASSWORD")
dbname := os.Getenv("POSTGRES_DBNAME")
// Construct connection string
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
// Open a connection to the PostgreSQL database
db, err = sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
// Create a new Gin router
router := gin.Default()
// Define a route to handle GET requests to /version
router.GET("/version", getVersion)
// Define a route to handle liveness probes at /healthz
router.GET("/healthz", livenessProbe)
// Define a route to handle readiness probes at /ready
router.GET("/ready", readinessProbe)
// Run the Gin router on port 8080
router.Run(":8080")
}
func getVersion(c *gin.Context) {
// Query the database for the PostgreSQL version
var version string
err := db.QueryRow("SELECT version();").Scan(&version)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"version": version})
}
func livenessProbe(c *gin.Context) {
// Perform a simple check to verify the health of the application
c.String(http.StatusOK, "OK")
}
func readinessProbe(c *gin.Context) {
c.String(http.StatusOK, "OK")
}