mattgodbolt / seasocks

Simple, small, C++ embeddable webserver with WebSockets support
BSD 2-Clause "Simplified" License
734 stars 120 forks source link

PathHandler for /:id style API #157

Open antoinewaugh opened 3 years ago

antoinewaugh commented 3 years ago

Hello,

I wish to follow the convention for my REST interface:

http://xxx.xxx.xxx.xxx:8080/resources/:id

Where GET http://xxx.xxx.xxx.xxx:8080/resources will return a list of resources, GET http://xxx.xxx.xxx.xxx:8080/resources/:id will return a single resource with id == :id.

Given id is part of the URI, my approach thus far has been to have a single PathHandler on resources, and inspect the CrackedURI::path()[0] element to infer if an id has been passed.

Is there a more elegant way of achieving this?

std::shared_ptr<seasocks::Response> ResourceEndpoint::handle(const CrackedUri &uri, const Request &request) {
 if (uri.path().size() == 1) {
    const auto base = uri.path()[0];
    if (base == "") {                                   
      switch (request.verb()) {
        case Request::Verb::Get: // return all resources
        ...
      }
    } else {
      try {
        const auto id = static_cast<uint32_t>(std::stol(base));   // return resource for 
        switch (request.verb()) {
        case Request::Verb::Get: // return resource for 'id' only
        ...
        }
      }
   }
}