forked from orderbynull/lottip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
84 lines (68 loc) · 1.75 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
package main
import (
"fmt"
"log"
"net/http"
"encoding/json"
"github.com/gorilla/websocket"
"github.com/olekukonko/tablewriter"
"github.com/orderbynull/lottip/chat"
)
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.Println(err)
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.Println(err)
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)))
log.Fatal(http.ListenAndServe(*guiAddr, nil))
}