-
Notifications
You must be signed in to change notification settings - Fork 0
/
responses.go
71 lines (62 loc) · 1.65 KB
/
responses.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
package webserver
import "strconv"
type Response struct {
StatusCode int
Headers map[string]string
Body string
MediaType string
}
func (r Response) build() []byte {
statusCode := strconv.Itoa(r.StatusCode)
statusMessage, ok := statusCodes[statusCode]
if !ok {
statusMessage = "Unknown"
}
response := "HTTP/1.1 " + statusCode + " " + statusMessage + "\r\n"
for k, v := range r.Headers {
response += k + ": " + v + "\r\n"
}
response += "Content-Length: " + strconv.Itoa(len(r.Body)) + "\r\n"
response += "Content-Type: " + r.MediaType + "\r\n"
response += "\r\n"
response += r.Body
return []byte(response)
}
func NewResponse(content string, status int, headers map[string]string, mediaType string) Response {
return Response{
StatusCode: status,
Headers: headers,
Body: content,
MediaType: mediaType,
}
}
func JSONResponse(content string, status int, headers map[string]string) Response {
if headers == nil {
headers = make(map[string]string)
}
if status == 0 {
status = 200
}
return NewResponse(content, status, headers, "application/json")
}
func HTMLResponse(content string, status int, headers map[string]string) Response {
if headers == nil {
headers = make(map[string]string)
}
if status == 0 {
status = 200
}
return NewResponse(content, status, headers, "text/html")
}
func TextResponse(content string, status int, headers map[string]string) Response {
if headers == nil {
headers = make(map[string]string)
}
if status == 0 {
status = 200
}
return NewResponse(content, status, headers, "text/plain")
}
func NotFoundResponse() Response {
return TextResponse("<h1>404 Not Found</h1>", 404, nil)
}