-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
59 lines (46 loc) · 1.58 KB
/
api.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
package chat
import (
"encoding/json"
"log"
"net/http"
)
// serveWs handles websocket requests from the peer. The hub needs to be populated
// with a *sqlx.DB reference, since we will need to store messages
func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("ServeWs upgrader error: %v", err)
return
}
// We can change this to JSON instead
clientID := r.URL.Query().Get("clientID")
// Client should have a reference to db, since this is the only way we can inject
// the db down there.
client := &Client{db: hub.db, ID: clientID, hub: hub, conn: conn, send: make(chan *Message, 256)}
client.hub.register <- client
client.hub.clients[clientID] = client
// Sending messages that were sent to the client when they were offline
client.PreviousMessages()
// This will broadcast that this client is online to all users who have this client as a contact
client.ShareStatus("online")
// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
go client.readPump()
}
// SubmitContacts
func SubmitContacts(currentUser string, dbPath string, w http.ResponseWriter, r *http.Request) {
db, err := OpenDb(dbPath)
if err != nil {
log.Printf("Could not open db: %v", err)
return
}
decoder := json.NewDecoder(r.Body)
var contacts []ContactsRequest
if err := decoder.Decode(&contacts); err != nil {
log.Printf("Error in parsing JSON: %v", err)
return
}
areUsers, err := addContactsToDB(currentUser, contacts, db)
w.Write(marshal(areUsers))
}