-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapisubs.go
90 lines (76 loc) · 2.3 KB
/
apisubs.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
package main
import (
"context"
"encoding/json"
"net/http"
"github.com/jackc/pgx/v4"
)
type Sub struct {
User string `json:"user"`
Channel string `json:"channel"`
}
// GetSubscriptions lists all subscriptions for a user.
func (srv *Shoutyface) GetSubscriptions(w http.ResponseWriter, r *http.Request) {
username := r.Header.Get("username")
var rows pgx.Rows
var err error
if username == "" {
sql := "select u.name,c.name from subs s inner join users u on u.id=s.uid inner join channels c on c.id=s.cid and s.uid=u.id;"
rows, err = srv.dbp.Query(context.Background(), sql)
} else {
sql := "select u.name,c.name from subs s inner join users u on u.name=$1 inner join channels c on c.id=s.cid and s.uid=u.id;"
rows, err = srv.dbp.Query(context.Background(), sql, username)
}
if err != nil {
srv.E("Error getting subscribers: %s", err.Error())
http.Error(w, "", http.StatusNotFound)
return
}
defer rows.Close()
var subs []Sub
for rows.Next() {
s := Sub{}
err = rows.Scan(&s.User, &s.Channel)
if err != nil {
srv.E("Error getting subscriptions: %s", err.Error())
}
subs = append(subs, s)
}
data, err := json.Marshal(subs)
if err != nil {
http.Error(w, "", http.StatusNotFound)
return
}
w.Write(data)
}
// PostSub subscribes a user to a channel.
func (srv *Shoutyface) PostSubscribe(w http.ResponseWriter, r *http.Request) {
username := r.Header.Get("username")
channel := r.Header.Get("channel")
if username == "" || channel == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
err := srv.Subscribe(username, channel)
if err != nil {
srv.E("Error subscribing user: %s", err.Error())
http.Error(w, err.Error(), http.StatusConflict)
return
}
http.Error(w, http.StatusText(http.StatusCreated), http.StatusCreated)
}
// DeleteSubscription unsubscribes a user from a channel.
func (srv *Shoutyface) DeleteSubscription(w http.ResponseWriter, r *http.Request) {
username := r.Header.Get("username")
channel := r.Header.Get("channel")
if username == "" || channel == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
err := srv.Unsubscribe(username, channel)
if err != nil {
srv.E("Error unsubscribing user: %s", err.Error())
http.Error(w, err.Error(), http.StatusNotFound)
return
}
}