v2 / examples / pico / raw_callback.v
39 lines · 30 sloc · 940 bytes · efc8f7fb3ef7e90a088db64ad2c68dd0698b90d5
Raw
1// vtest build: !solaris
2module main
3
4import net
5import picoev
6
7const port = 8080
8
9const http_response = 'HTTP/1.1 200 OK\r\nContent-type: text/html\r\nContent-length: 18\r\n\r\nHello from Picoev!'
10
11fn main() {
12 println('Starting webserver on http://localhost:${port}/ ...')
13 mut pico := picoev.new(
14 port: port
15 raw_cb: handle_conn
16 )!
17 pico.serve()
18}
19
20fn handle_conn(mut pv picoev.Picoev, fd int, _events int) {
21 // setup a nonblocking tcp connection
22 mut conn := &net.TcpConn{
23 sock: net.tcp_socket_from_handle_raw(fd)
24 handle: fd
25 is_blocking: false
26 }
27
28 mut buf := []u8{len: 4096}
29 // read data from the tcp connection
30 conn.read(mut buf) or { eprintln('could not read data from socket') }
31
32 println('received data:')
33 println(buf.bytestr())
34
35 conn.write(http_response.bytes()) or { eprintln('could not write response') }
36
37 // remove the socket from picoev's event loop and close the connection
38 pv.close_conn(fd)
39}
40