-
Notifications
You must be signed in to change notification settings - Fork 0
/
apichannels.go
71 lines (61 loc) · 1.7 KB
/
apichannels.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
package main
import (
"context"
"encoding/json"
"net/http"
"strings"
)
func (srv *Shoutyface) PostChannel(w http.ResponseWriter, r *http.Request) {
channel := r.Header.Get("channel")
if channel == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
sql := "insert into channels(name) values($1)"
_, err := srv.dbp.Exec(context.Background(), sql, channel)
if err != nil {
if strings.Contains(err.Error(), "duplicate") {
http.Error(w, "", http.StatusNotModified)
return
}
srv.E("Error adding channel: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// DeleteChannel fom database.
func (srv *Shoutyface) DeleteChannel(w http.ResponseWriter, r *http.Request) {
channel := r.Header.Get("channel")
if channel == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
ct, err := srv.dbp.Exec(context.Background(), "delete from channels where name=$1;", channel)
if err != nil || ct.RowsAffected() == 0 {
http.Error(w, "", http.StatusNotFound)
return
}
}
// Channel for JSON result.
type Channel struct {
// Name of the channel.
Name string `json:"channel"`
}
// GetChannels available.
func (srv *Shoutyface) GetChannels(w http.ResponseWriter, r *http.Request) {
rows, err := srv.dbp.Query(context.Background(), "select name from channels;")
if err != nil {
srv.E("Error listing channels: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var channels []Channel
for rows.Next() {
var c Channel
rows.Scan(&c.Name)
channels = append(channels, c)
}
data, _ := json.Marshal(channels)
w.Write([]byte(data))
}