-
Notifications
You must be signed in to change notification settings - Fork 69
/
web-server.go
59 lines (44 loc) · 1.08 KB
/
web-server.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
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
"net/http"
"os"
)
func hello(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "Hello")
}
func healthz(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "Healthy")
}
func dataHandler(w http.ResponseWriter, _ *http.Request) {
db := CreateCon()
err := db.Ping()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
fmt.Fprintf(w, "Database Connected")
}
}
func main() {
http.HandleFunc("/", hello)
http.HandleFunc("/healthz", healthz)
http.HandleFunc("/data", dataHandler)
http.ListenAndServe("0.0.0.0:8080", nil)
}
/*Create sql database connection*/
func CreateCon() *sql.DB {
user := os.Getenv("DB_USER")
pass := os.Getenv("DB_PASSWORD")
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
connStr := fmt.Sprintf("postgres://%v:%v@%v:%v?sslmode=disable", user, pass, host, port)
fmt.Printf("Database Connection String: %v \n", connStr)
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatalf("ERROR: %v", err)
}
return db
}