-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (53 loc) · 1.42 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
package main
import (
"fmt"
"io"
"log"
"net"
"os"
"github.com/joho/godotenv"
)
func main() {
proxyAddr := ":5432"
listener, err := net.Listen("tcp", proxyAddr)
if err != nil {
log.Fatal("failed to create tcp server")
}
defer listener.Close()
fmt.Printf("Proxy listening on %s\n", proxyAddr)
for {
clientConn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept connection: %v", err)
continue
}
go handleConnection(clientConn)
}
}
func handleConnection(clientConn net.Conn) {
defer clientConn.Close()
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
dbHost := os.Getenv("PG_DATABASE_HOST")
dbPort := os.Getenv("PG_DATABASE_PORT")
// Establish a new TCP connection to the actual PostgreSQL server
dbConn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", dbHost, dbPort))
if err != nil {
log.Printf("Failed to connect to database: %v", err)
return
}
defer dbConn.Close()
// Proxy data between client and database
go func() {
_, err := io.Copy(dbConn, clientConn)
if err != nil {
log.Printf("Error copying data from client to DB: %v", err)
}
}()
_, err = io.Copy(clientConn, dbConn)
if err != nil {
log.Printf("Error copying data from DB to client: %v", err)
}
}