forked from semaphoreci-demos/semaphore-demo-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (69 loc) · 1.75 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
78
79
80
81
package main
import (
"database/sql"
"fmt"
"net/http"
"os"
"time"
_ "github.com/lib/pq"
)
func myHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Serving: %s\n", r.URL.Path)
fmt.Printf("Served: %s\n", r.Host)
}
func timeHandler(w http.ResponseWriter, r *http.Request) {
t := time.Now().Format(time.RFC1123)
Body := "The current time is:"
fmt.Fprintf(w, "<h1 align=\"center\">%s</h1>", Body)
fmt.Fprintf(w, "<h2 align=\"center\">%s</h2>\n", t)
fmt.Fprintf(w, "Serving: %s\n", r.URL.Path)
fmt.Printf("Served time for: %s\n", r.Host)
}
func getData(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Serving: %s\n", r.URL.Path)
fmt.Printf("Served: %s\n", r.Host)
connStr := "user=postgres dbname=s2 sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
fmt.Fprintf(w, "<h1 align=\"center\">%s</h1>", err)
return
}
rows, err := db.Query("SELECT * FROM users")
if err != nil {
fmt.Fprintf(w, "<h3 align=\"center\">%s</h3>\n", err)
return
}
defer rows.Close()
for rows.Next() {
var id int
var firstName string
var lastName string
err = rows.Scan(&id, &firstName, &lastName)
if err != nil {
fmt.Fprintf(w, "<h1 align=\"center\">%s</h1>\n", err)
return
}
fmt.Fprintf(w, "<h3 align=\"center\">%d, %s, %s</h3>\n", id, firstName, lastName)
}
err = rows.Err()
if err != nil {
fmt.Fprintf(w, "<h1 align=\"center\">%s</h1>", err)
return
}
}
func main() {
PORT := ":8001"
arguments := os.Args
if len(arguments) != 1 {
PORT = ":" + arguments[1]
}
fmt.Println("Using port number: ", PORT)
http.HandleFunc("/time", timeHandler)
http.HandleFunc("/getdata", getData)
http.HandleFunc("/", myHandler)
err := http.ListenAndServe(PORT, nil)
if err != nil {
fmt.Println(err)
return
}
}