...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package server
18
19 import (
20 "encoding/json"
21 "fmt"
22 "net/http"
23 )
24
25 type Response interface {
26 Headers() map[string]string
27 Status() int
28 Bytes() []byte
29 }
30
31 type bytesResponse struct {
32 StatusCode int
33 ContentType string
34 Body []byte
35 }
36
37 func (r bytesResponse) Bytes() []byte {
38 return r.Body
39 }
40
41 func (r bytesResponse) Status() int {
42 return r.StatusCode
43 }
44
45 func (r bytesResponse) Headers() map[string]string {
46 return map[string]string{
47 "Content-Length": fmt.Sprintf("%d", len(r.Body)),
48 "Content-Type": r.ContentType,
49 }
50 }
51
52 func BytesResponse(body []byte, contentType string) Response {
53 return &bytesResponse{
54 StatusCode: http.StatusOK,
55 ContentType: contentType,
56 Body: body,
57 }
58 }
59
60 func StringResponse(statusCode int, body string) Response {
61 return &bytesResponse{
62 StatusCode: statusCode,
63 ContentType: "text/plain",
64 Body: []byte(body + "\r\n"),
65 }
66 }
67
68 func ErrorResponse(statusCode int) Response {
69 return &bytesResponse{
70 StatusCode: statusCode,
71 ContentType: "text/plain",
72 Body: []byte(http.StatusText(statusCode) + "\r\n"),
73 }
74 }
75
76 var AccessDeniedResponse Response = &bytesResponse{
77 StatusCode: http.StatusForbidden,
78 ContentType: "text/plain",
79 Body: []byte("Access denied\r\n"),
80 }
81
82 func JSONResponse(data interface{}) (Response, error) {
83 blob, err := json.Marshal(data)
84 if err != nil {
85 return nil, err
86 }
87 return &bytesResponse{
88 StatusCode: http.StatusOK,
89 ContentType: "application/json",
90 Body: blob,
91 }, nil
92 }
93
94 func writeResponse(writer http.ResponseWriter, response Response) {
95 for k, v := range response.Headers() {
96 writer.Header().Set(k, v)
97 }
98 writer.WriteHeader(response.Status())
99 writer.Write(response.Bytes())
100 }
101
View as plain text