Display a random image with vibe.d

Christian Köstlin christian.koestlin at gmail.com
Mon Jun 21 23:53:08 UTC 2021


On 2021-06-20 17:14, vnr wrote:
> On Sunday, 20 June 2021 at 14:28:26 UTC, jfondren wrote:
>> On Sunday, 20 June 2021 at 13:58:22 UTC, vnr wrote:
>>>
>>> Thanks for the answers, I understand better what is going on.
>>>
>>> So, what should I do to make my server respond with a random image, 
>>> and not the random image page? I'm fairly new to vibe.d, so I don't 
>>> yet know the intricacies of how to handle this style of thing and I 
>>> couldn't find how to do it in the documentation.
>>>
>>> Thank you.
>>
>> Responding with a random image is an option, but what you have is
>> a good start, you just need to also serve images on request.
>>
>> I'm very distracted right now or I would've included more in my
>> earlier post, but Vibe's online documentation has what you need.
>>
>> Try, especially, https://vibed.org/docs#http-routing
>>
>> You want a route for the random-image page, and you want to serve
>> static files under images/
> 
> Great, thanks a lot, it works as expected! Here is the code used 
> (app.d), for those who are interested:
> 
> ```
> import vibe.vibe;
> 
> void main()
> {
> 
>          auto router = new URLRouter;
>          router.get("/", &index);
>          router.get("*", serveStaticFiles("public"));
> 
>          auto settings = new HTTPServerSettings;
>          settings.bindAddresses = ["::1", "127.0.0.1"];
>          settings.port = 8080;
> 
>          auto listener = listenHTTP(settings, router);
>          scope (exit) listener.stopListening();
> 
>          logInfo("Please open http://127.0.0.1:8080/ in your browser.");
>          runApplication();
>      }
> 
>      /// The index page
>      void index(HTTPServerRequest req, HTTPServerResponse res)
>      {
>          import std.random;
>          import std.format;
> 
>          auto rnd = Random(unpredictableSeed);
>          const auto rndimg = format("/images/rndimg/img%d.jpg", 
> uniform(1, 27, rnd));
> 
>          res.render!("index.dt", req, rndimg);
>      }
>      ```
The Random object should only be created once, but here its created for 
every request.
1. It is relatively slow to reinitialize it
2. If you really want to have uniform distribution its probably better 
to not throw the UniformRandomNumberGenerator generator away.

You can simplify that by using just uniform(1, 27) (it should fallback 
to the default rndGen that is initialized per thread 
(https://dlang.org/library/std/random/rnd_gen.html).

here a benchmark of both functions:

```
import std;
import std.datetime.stopwatch;

auto onlyUniform() {
   return uniform(1, 27);
}
auto withNewRandom() {
     auto rnd = Random(unpredictableSeed);
     return uniform(1, 27, rnd);
}
void main() {
   100_000.benchmark!(onlyUniform, withNewRandom).writeln;
}
```


More information about the Digitalmars-d-learn mailing list