-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (56 loc) · 2.09 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
package main
import (
"context"
"database/sql"
"fmt"
"log"
"net/http"
"os"
"strings"
_ "github.com/lib/pq"
)
const sqlConnectionStringVar = "PG_CONNECTION_STRING"
const listenAddress = ":8080"
// guessedEnvironment is used to illustrate that we can run this app in different kinds of runtimes.
// expand the init function to support more identifications.
var guessedEnvironment = "unknown"
func init() {
raw, _ := os.ReadFile("/etc/resolv.conf")
if strings.Contains(string(raw), "cluster.local") {
guessedEnvironment = "kubernetes"
} else if strings.Contains(string(raw), "Docker") {
guessedEnvironment = "docker"
}
}
func main() {
// First, get the connection string and attempt a connection or fail
connStr := os.Getenv(sqlConnectionStringVar)
conn, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatalf("failed to open the database %s=%s: %v", sqlConnectionStringVar, connStr, err)
}
defer conn.Close()
// Second, wait until we get a successful connection to the db
if err := conn.PingContext(context.TODO()); err != nil {
log.Fatalf("failed to connect to database %s=%s: %v", sqlConnectionStringVar, connStr, err)
}
log.Printf("successfully connected to database %s=%s", sqlConnectionStringVar, connStr)
// Third, link the handler function
http.HandleFunc("GET /{$}", func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("X-Env", guessedEnvironment)
var versionOutput string
if err := conn.QueryRowContext(request.Context(), "SELECT version()").Scan(&versionOutput); err != nil {
writer.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprintf(writer, "Failed to get sql version: %v\n", err)
log.Printf("%s %s %s status=500: %v\n", request.Host, request.Method, request.RequestURI, err)
} else {
_, _ = fmt.Fprintf(writer, "SQL VERSION: %s\n", versionOutput)
log.Printf("%s %s %s status=200\n", request.Host, request.Method, request.RequestURI)
}
})
// Finally, run the http server
log.Print("starting server")
if err := http.ListenAndServe(listenAddress, http.DefaultServeMux); err != nil {
log.Fatal(err.Error())
}
}