forked from brainz80/lottip
-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
87 lines (71 loc) · 1.98 KB
/
http.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
package main
import (
"fmt"
"github.com/rs/zerolog/log"
"lottip/chat"
"net/http"
"encoding/json"
"github.com/gorilla/websocket"
"github.com/olekukonko/tablewriter"
)
const (
websocketRoute = "/ws"
webRoute = "/"
)
func runHttpServer(hub *chat.Hub) {
// Websockets endpoint
http.HandleFunc(websocketRoute, func(w http.ResponseWriter, r *http.Request) {
upgr := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}
conn, err := upgr.Upgrade(w, r, nil)
if err != nil {
log.Error().Err(err).Msg("Could not upgrade connection from " + r.RemoteAddr + " to websocket")
return
}
// Proper handling 'close' message from the peer
// See https://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages for details
go func() {
if _, _, err := conn.NextReader(); err != nil {
conn.Close()
}
}()
client := chat.NewClient(conn, hub)
hub.RegisterClient(client)
go client.Process()
})
// Query execution endpoint
http.HandleFunc("/execute", func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Error().Err(err).Msg("Could not parse query execution request from " + r.RemoteAddr)
return
}
type Data struct {
Database string
Query string
Parameters []string
}
var parsedData Data
data := r.PostFormValue("data")
json.Unmarshal([]byte(data), &parsedData)
columns, rows, err := getQueryResults(parsedData.Database, parsedData.Query, parsedData.Parameters, *mysqlDsn)
if err != nil {
fmt.Fprint(w, err.Error())
return
}
if len(columns) > 0 {
table := tablewriter.NewWriter(w)
table.SetAutoFormatHeaders(false)
table.SetColWidth(1000)
table.SetHeader(columns)
table.AppendBulk(rows)
table.Render()
} else {
fmt.Fprint(w, "Empty response")
}
})
http.Handle(webRoute, http.FileServer(FS(*useLocalUI)))
err := http.ListenAndServe(*guiAddr, nil)
if err != nil {
log.Fatal().Err(err).Msg("Could not start HTTP server at " + *guiAddr)
}
}