-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.go
More file actions
65 lines (55 loc) · 1.67 KB
/
response.go
File metadata and controls
65 lines (55 loc) · 1.67 KB
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
package wstf
import (
"fmt"
"github.com/gorilla/websocket"
)
type Response struct {
// The reference of wstf Connection.
Connection *Connection `json:"-"`
// Shortcut for Connection.Locals
ConnectionLocals map[string]interface{}
// The reference of corresponding wstf Request.
Request *Request
// JSON Response that will be sent as response to corresponding request.
JsonResponse *JsonResponse
// A map that contains response local variables scoped to the request.
// This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
Locals map[string]interface{}
}
func NewResponse(connection *Connection, connectionLocals map[string]interface{}, request *Request) *Response {
return &Response{
connection,
connectionLocals,
request,
&JsonResponse{Id: request.Id},
make(map[string]interface{}),
}
}
// The raw methods to access Response.JsonResponse.
// Set status code.
func (m *Response) SetStatusCode(statusCode int) *Response {
m.JsonResponse.Status = statusCode
return m
}
// Set header.
func (m *Response) SetHeader(key, value string) {
m.JsonResponse.Headers[key] = value
}
// Set json-response body.
func (m *Response) SetBody(body interface{}) *Response {
m.JsonResponse.Body = body
return m
}
// Finish the request.
func (m *Response) End() error {
return m.Write(websocket.TextMessage, []byte(m.JsonResponse.ToJson()))
}
// Response to client.
func (m *Response) Write(mt int, message []byte) error {
if m.Connection == nil {
fmt.Println("DEBUGGING MODE: Sending Message: ", string(message))
return nil
}
err := m.Connection.WebSocketConn.WriteMessage(mt, message)
return err
}