-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
70 lines (53 loc) · 1.21 KB
/
response.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
/* Gavin Langdon
* Network Programming
* Spring 2013
* Chat server
*/
// A response is sent back to the client upon sending a command
package main
import (
"fmt"
)
type Response struct {
data []byte
Quit bool // Whether or not this response should cause the client to be disconnected
}
func NewResponse(code string) Response {
data := append([]byte(code), ' ')
return Response{data, false}
}
func NewOkResponse() Response {
return NewResponse("OK")
}
func NewErrorResponse(err error) Response {
rs := NewResponse("ERROR")
rs.AppendString(err.Error())
return rs
}
func NewFatalErrorResponse(err error) Response {
rs := NewErrorResponse(err)
rs.Quit = true
return rs
}
func NewQuitResponse() Response {
rs := NewResponse("TIUQ")
rs.Quit = true
return rs
}
func (rs *Response) AppendString(s string) {
rs.Append([]byte(s))
}
func (rs *Response) Append(data []byte) {
data = append(data, ' ')
rs.data = append(rs.data, data...)
}
func (rs *Response) String() string {
return string(rs.data)
}
func (rs *Response) WriteTo(c *Client) (n int, err error) {
if *VerboseMode {
fmt.Println("SENT to", c.String()+":", rs)
}
rs.data = append(rs.data, "\n"...)
return c.Write(rs.data)
}