Vibe.d rest & web service?

Steven Schveighoffer schveiguy at yahoo.com
Wed Feb 7 18:47:05 UTC 2018


On 2/7/18 12:04 PM, Nicholas Wilson wrote:
> Is it possible to have some urls routed to serve content and some to 
> receive JSON in the same class? Basically I want:
> 
> shared static this()
> {
>      auto router = new URLRouter;
>      auto a = new MyInterface;
>      router.registerWebInterface(new MyInterface); //?? selective 
> combination
>      router.registerRestInterface(new MyInterface); //??
>      auto settings = new HTTPServerSettings;
>      settings.port = 8080;
>      settings.bindAddresses = ["::1","127.0.0.1"];
>      listenHTTP(settings, router);
> }
> 
> class MyInterface
> {
>      SomeData[] items;
>      // Get
>      void index()
>      {
>          render!("index.dt");
>      }
>      // Get
>      void getPage()
>      {
>          render!("page.dt", items);
>      }
> 
>      // REST -> receive d as JSON.
>      void postGiveMeData(SomeData d)
>      {
>          synchronized
>          {
>              items ~= d;
>          }
>      }
> }

Yes you can, but it's not pretty.

interface MyInterface
{
    void postGiveMeData(SomeData d);
}

class MyInterfaceImpl : MyInterface
{
    void postGiveMeData(SomeData d) { ... }
    void getPage() { ... }
    void index() { ... }
}

auto myI = new MyInterfaceImpl;
router.registerRestInterface(myI);
router.get("/route/to/getPage", &myI.getPage);
router.get("/route/to/index", &myI.index);

This worked for me, but note that my "non-rest" function was static, so 
I didn't need to worry about instances. I'm not sure if the above works 
exactly right for you.

However, I would recommend actually not doing this for your purpose. My 
case was different -- I still wanted routes that were REST routes, but I 
wanted to control the result streaming (the vibe.d return value doesn't 
work with ranges, so I would have had to construct essentially my entire 
database in an array so I could return it).

In your case, I think you are better off using 2 classes, and one shared 
data storage area.

-Steve


More information about the Digitalmars-d-learn mailing list