| 1 | // vtest build: !solaris |
| 2 | module main |
| 3 | |
| 4 | import net |
| 5 | import picoev |
| 6 | |
| 7 | const port = 8080 |
| 8 | |
| 9 | const http_response = 'HTTP/1.1 200 OK\r\nContent-type: text/html\r\nContent-length: 18\r\n\r\nHello from Picoev!' |
| 10 | |
| 11 | fn 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 | |
| 20 | fn 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 | |