forked from taiyoh/graphqlws-subscription-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifier.go
66 lines (58 loc) · 1.52 KB
/
notifier.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
package gss
import (
"bytes"
"encoding/json"
"errors"
"net/http"
)
type NotificationHandler struct {
notifyChan chan *RequestData
}
type NotificationResponse struct {
Success bool `json:"success"`
Errors []string `json:"errors"`
}
func successResponse() []byte {
r := &NotificationResponse{Success: true}
b, _ := json.Marshal(r)
return b
}
func failResponse(errs []string) []byte {
r := &NotificationResponse{Success: false, Errors: errs}
b, _ := json.Marshal(r)
return b
}
func readJSONContent(req *http.Request) (*RequestData, error) {
if contentType := req.Header.Get("Content-Type"); contentType != "application/json" {
return nil, errors.New("Content-Type requires application/json")
}
bufbody := new(bytes.Buffer)
if _, err := bufbody.ReadFrom(req.Body); err != nil {
return nil, err
}
data, err := NewRequestDataFromBytes(bufbody.Bytes())
if err != nil {
return nil, err
}
return data, nil
}
func (h *NotificationHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
w.Header().Set("Content-Type", "application/json")
if req.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write(failResponse([]string{"not allowed method"}))
return
}
data, err := readJSONContent(req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write(failResponse([]string{err.Error()}))
return
}
h.notifyChan <- data
w.Write(successResponse())
}
func NewNotifyHandler(ch chan *RequestData) http.Handler {
return &NotificationHandler{notifyChan: ch}
}