I’m likely repeating myself because this situation is very common. But I still can’t figure out how to properly work with files to avoid issues with open file descriptors.
The file example.txt
contains plain text. I’d like to read such files in my queries and perform operations on them. In this example, I’m using the most basic approach. I can’t understand why I’m getting exceptions related to file descriptors. I realize that when returning to the main loop, the file likely remains open. How can I correctly and properly implement this approach? I couldn’t find a simple implementation of this in the examples.
import vibe.http.server;
import vibe.http.router;
import vibe.core.core;
import vibe.core.file;
string getText()
{
auto file = openFile("example.txt", FileMode.read);
scope (exit)
file.close();
ubyte[] buffer;
buffer.length = file.size;
file.read(buffer);
return cast(string) buffer.idup;
}
void handleRequest(HTTPServerRequest req, HTTPServerResponse res)
{
res.writeBody(getText());
}
int main()
{
auto settingsHTTP = new HTTPServerSettings;
settingsHTTP.port = 8080;
settingsHTTP.bindAddresses = ["127.0.0.1"];
auto router = new URLRouter;
router.get("/", &handleRequest);
auto listenerHTTP = listenHTTP(settingsHTTP, router);
scope (exit)
listenerHTTP.stopListening();
return runApplication();
}
result ctrl+c
Listening for requests on http://127.0.0.1:8080/
^CReceived signal 2. Shutting down.
Stopped to listen for HTTP requests on 127.0.0.1:8080
Warning (thread: main): leaking eventcore driver because there are still active handles
FD 8 (streamSocket)
Use '-debug=EventCoreLeakTrace' to show where the instantiation happened
Warning (thread: main): leaking eventcore driver because there are still active handles
FD 8 (streamSocket)
Use '-debug=EventCoreLeakTrace' to show where the instantiation happened