Parsing paths in a microservice

A common task in web development is to use functions that work with persistent storage. These functions are often called create, read, update, and delete (CRUD) functions. They are the most common operations with data.

We can implement a CRUD set for our service, but first we have to identify the entity that we want to work with. Imagine that we need three types of entities: users, articles, and comments. In this case, I recommend that you separate the microservices, because the users microservice is responsible for identity, the articles microservice is responsible for the content, and the comments microservice handles content. However, you would get more benefits if you could reuse these entities for more than one context.

Before we implement all the handlers, we need a helper function that creates empty responses with the corresponding HTTP status codes:

fn response_with_code(status_code: StatusCode) -> Response<Body> {
Response::builder()
.status(status_code)
.body(Body::empty())
.unwrap()
}

This function carries out a few simple actions  it expects a status code, creates a new response builder, sets that status, and adds an empty body.

We can now add a new request handler that checks three path variants:

  • The index page (path /)
  • Actions with user data (prefix /user/)
  • Other paths

We can use the match expression to fulfill all of these cases. Add the following code to the microservices_handler function:

    let response = {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") => {
Response::new(INDEX.into())
},
(method, path) if path.starts_with(USER_PATH) => {
unimplemented!();
},
_ => {
response_with_code(StatusCode::NOT_FOUND)
},
}
};
future::ok(response)

As you can see, we used an if expression in the second branch to detect that the path starts with the /user/ prefix. This prefix is actually stored in the USER_PATH constant:

const USER_PATH: &str = "/user/";

Unlike the previous example, in this case we'll use our brand new response_with_code function to return a NOT_FOUND HTTP response. We also assign a response to the response variable and use it to create a Future instance with the future::ok function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.78.83