-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
executable file
·99 lines (80 loc) · 1.86 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package go_remote
import (
"context"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"github.com/gorilla/websocket"
)
type key int
var UserValue = key(1)
var ConnectionValue = key(2)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type StatusInfo struct {
Hub HubStatus
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, err := s.Connect(r)
if err != nil {
serveError(w, err)
return
}
isSocketStart := r.Method == "GET" && r.URL.Query().Get("ws") != ""
if r.Method == "GET" && !isSocketStart {
serveJSON(w, s.GetAPI(ctx))
return
}
if !isSocketStart && r.Method != "POST" {
serveError(w, errors.New("only post and get request types are supported"))
return
}
if isSocketStart {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
serveError(w, err)
return
}
userID, _ := ctx.Value(UserValue).(int)
cid, cidExists := ctx.Value(ConnectionValue).(int)
if !cidExists {
cid := nextId()
ctx = context.WithValue(ctx, ConnectionValue, cid)
}
client := Client{Server: s, conn: conn, Send: make(chan []byte, 256), User: userID, ConnID: cid }
client.ctx = ctx
go client.Start()
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
serveError(w, err)
return
}
res := s.Process(body, ctx)
serveJSON(w, res)
}
func (s *Server) ServeStatus(w http.ResponseWriter, _ *http.Request) {
serveJSON(w, StatusInfo{Hub: *s.Events.Status()})
}
func serveError(w http.ResponseWriter, err error) {
text := err.Error()
log.Errorf(text)
http.Error(w, text, 500)
}
func serveJSON(w http.ResponseWriter, res interface{}) {
w.Header().Set("Content-type", "text/json")
out, _ := json.Marshal(res)
w.Write(out)
}
var idCounter ConnectionID
func nextId() ConnectionID {
idCounter += 1
return idCounter
}