@@ -17,6 +17,47 @@ Libevent additionally provides a sophisticated framework for buffered network IO
1717- [ Libevent] ( https://libevent.org/ ) 2.1.12 or later
1818- Nim 2.0 or later
1919
20+ ## Create a simple HTTP server
21+
22+ Using the bindings in this package, you can create a simple HTTP server like this:
23+ ``` nim
24+ import std/httpcore
25+ import pkg/libevent
26+
27+ from std/net import Port
28+
29+ let eventBase = event_base_new()
30+ assert eventBase != nil, "Could not create event base"
31+
32+ let httpServer = evhttp_new(eventBase)
33+ assert httpServer != nil, "Could not create HTTP server"
34+
35+ template respond(str: string, code: HttpCode = HttpCode(200)) =
36+ let buf = evhttp_request_get_output_buffer(req)
37+ assert buf != nil # should never be nil
38+ assert evbuffer_add(buf, str.cstring, str.len.csize_t) == 0
39+ evhttp_send_reply(req, code.cint, "", buf)
40+ return
41+
42+ proc onRequest(req: ptr evhttp_request, arg: pointer) {.cdecl.} =
43+ let uri = evhttp_request_get_uri(req)
44+ let path = if uri.len > 0: uri else: "/"
45+ let httpMethod = evhttp_request_get_command(req)
46+ case path
47+ of "/":
48+ respond("Hello, World!")
49+ else:
50+ respond("Not Found", HttpCode(404))
51+
52+ assert evhttp_bind_socket(httpServer, "0.0.0.0", uint16(8000)) == 0
53+ evhttp_set_gencb(httpServer, onRequest, nil)
54+ assert event_base_dispatch(eventBase) > -1, "Could not start event loop"
55+
56+ # cleanup after event loop ends, which it never does in this example
57+ evhttp_free(httpServer)
58+ event_base_free(eventBase)
59+ ```
60+
2061
2162### ❤ Contributions & Support
2263- 🐛 Found a bug? [ Create a new Issue] ( https://github.com/openpeeps/libevent-nim/issues )
0 commit comments