v / vlib / picohttpparser / response.c.v
122 lines · 104 sloc · 2.39 KB · a87a4d73b9ab25cfff0822f4e94cf2a2d9e64323
Raw
1module picohttpparser
2
3$if !windows {
4 #include <sys/socket.h>
5}
6
7pub struct Response {
8pub:
9 fd int
10 date &u8 = unsafe { nil }
11 buf_start &u8 = unsafe { nil }
12pub mut:
13 buf &u8 = unsafe { nil }
14}
15
16@[inline]
17pub fn (mut r Response) write_string(s string) {
18 unsafe {
19 vmemcpy(r.buf, s.str, s.len)
20 r.buf += s.len
21 }
22}
23
24@[inline]
25pub fn (mut r Response) http_ok() &Response {
26 r.write_string('HTTP/1.1 200 OK\r\n')
27 return unsafe { r }
28}
29
30@[inline]
31pub fn (mut r Response) header(k string, v string) &Response {
32 r.write_string(k)
33 r.write_string(': ')
34 r.write_string(v)
35 r.write_string('\r\n')
36 return unsafe { r }
37}
38
39@[inline]
40pub fn (mut r Response) header_date() &Response {
41 r.write_string('Date: ')
42 unsafe {
43 vmemcpy(r.buf, r.date, 29)
44 r.buf += 29
45 }
46 r.write_string('\r\n')
47 return unsafe { r }
48}
49
50@[inline]
51pub fn (mut r Response) header_server() &Response {
52 r.write_string('Server: V\r\n')
53 return unsafe { r }
54}
55
56@[inline]
57pub fn (mut r Response) content_type(s string) &Response {
58 r.write_string('Content-Type: ')
59 r.write_string(s)
60 r.write_string('\r\n')
61 return unsafe { r }
62}
63
64@[inline]
65pub fn (mut r Response) html() &Response {
66 r.write_string('Content-Type: text/html\r\n')
67 return unsafe { r }
68}
69
70@[inline]
71pub fn (mut r Response) plain() &Response {
72 r.write_string('Content-Type: text/plain\r\n')
73 return unsafe { r }
74}
75
76@[inline]
77pub fn (mut r Response) json() &Response {
78 r.write_string('Content-Type: application/json\r\n')
79 return unsafe { r }
80}
81
82@[inline]
83pub fn (mut r Response) body(body string) {
84 r.write_string('Content-Length: ')
85 unsafe {
86 r.buf += u64toa(r.buf, u64(body.len)) or { panic(err) }
87 }
88 r.write_string('\r\n\r\n')
89 r.write_string(body)
90}
91
92@[inline]
93pub fn (mut r Response) http_404() {
94 r.write_string('HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n')
95}
96
97@[inline]
98pub fn (mut r Response) http_405() {
99 r.write_string('HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n')
100}
101
102@[inline]
103pub fn (mut r Response) http_500() {
104 r.write_string('HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n')
105}
106
107@[inline]
108pub fn (mut r Response) raw(response string) {
109 r.write_string(response)
110}
111
112fn C.send(sockfd i32, buf voidptr, len usize, flags i32) i32
113
114@[inline]
115pub fn (mut r Response) end() int {
116 n := int(i64(r.buf) - i64(r.buf_start))
117 // use send instead of write for windows compatibility
118 if C.send(r.fd, r.buf_start, n, 0) != n {
119 return -1
120 }
121 return n
122}
123