forked from fhirbase/fhirbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
189 lines (144 loc) · 4.08 KB
/
web.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gobuffalo/packr"
"github.com/jackc/pgx"
jsoniter "github.com/json-iterator/go"
"github.com/urfave/cli"
)
var pool *pgx.ConnPool
func qHandler(w http.ResponseWriter, r *http.Request) {
sql := r.URL.Query().Get("query")
w.Header().Set("Content-Type", "application/json")
if len(sql) == 0 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("{\"message\": \"Please provide 'query' query-string param\"}"))
return
}
conn, err := pool.Acquire()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("{\"message\": \"Cannot acquire DB connection\"}"))
return
}
defer pool.Release(conn)
stream := jsoniter.ConfigFastest.BorrowStream(w)
defer jsoniter.ConfigFastest.ReturnStream(stream)
rows, err := conn.Query(sql)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
stream.WriteVal(map[string]string{
"message": err.Error(),
})
stream.Flush()
return
}
defer rows.Close()
stream.WriteObjectStart()
stream.WriteObjectField("columns")
stream.WriteVal(rows.FieldDescriptions())
stream.WriteMore()
stream.WriteObjectField("rows")
stream.WriteArrayStart()
hasRows := rows.Next()
for hasRows {
vals, err := rows.Values()
if err == nil {
stream.WriteVal(vals)
} else {
stream.WriteNil()
}
hasRows = rows.Next()
if hasRows {
stream.WriteMore()
}
}
stream.WriteArrayEnd()
stream.WriteObjectEnd()
stream.Flush()
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
conn, err := pool.Acquire()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("{\"message\": \"Cannot acquire DB connection\"}"))
return
}
defer pool.Release(conn)
rows, err := conn.Query("SELECT 1+1")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("{ \"message\": \"cannot perform query\" }"))
return
}
defer rows.Close()
w.Write([]byte("{ \"message\": \"ich bin gesund\" }"))
}
func logging(logger *log.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
logger.Println(r.Method, r.URL, r.RemoteAddr, r.UserAgent())
}()
next.ServeHTTP(w, r)
})
}
}
// WebAction starts HTTP server and serves basic FB API
func WebCommand(c *cli.Context) error {
webHost := c.String("webhost")
webPort := c.Uint("webport")
addr := fmt.Sprintf("%s:%d", webHost, webPort)
var box http.FileSystem
if os.Getenv("DEV") == "" {
box = packr.NewBox("./web")
} else {
box = http.Dir("./web")
}
mainConfig := GetPgxConnectionConfig(nil)
connStr := fmt.Sprintf("dbname=%s sslmode=disable user=%s password=%s host=%s port=%d",
mainConfig.Database, mainConfig.User, mainConfig.Password, mainConfig.Host, mainConfig.Port)
var err error
pool, err = pgx.NewConnPool(pgx.ConnPoolConfig{ConnConfig: mainConfig})
if err != nil {
fmt.Fprintln(os.Stderr, "Unable to connect to database:", err)
os.Exit(1)
}
logger := log.New(os.Stdout, "", log.LstdFlags)
logger.Printf("Connected to database %s\n", connStr)
router := http.NewServeMux()
router.Handle("/", http.FileServer(box))
router.HandleFunc("/q", qHandler)
router.HandleFunc("/health", healthHandler)
server := &http.Server{
Addr: addr,
Handler: logging(logger)(router),
ErrorLog: logger,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
idleConnsClosed := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
<-sigint
if err := server.Shutdown(context.Background()); err != nil {
logger.Printf("HTTP server Shutdown: %v\n", err)
}
close(idleConnsClosed)
}()
logger.Printf("Starting web server on %s\n", addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatalf("Could not listen on %s: %v\n", addr, err)
}
logger.Println("Server stopped")
return nil
}