Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Rust Web frameworks?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the Rust Web frameworks". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what the Rust Web framework is.

Common Web frameworks for Rust

There are dozens of Web frameworks known to Rust, which are listed in detail in flosse's rust-web-framework-comparison open source project (see Resources at the end of the article for a link). However, it is a pity that there is no official support or recommended Web framework, so we pick out a few comparisons for the simple use of the actual project, hoping to give you a reference when choosing a framework.

The difficulties of Rust Web Framework

Before comparing these frameworks, let's review the difficulties of the Rust language in dealing with Web processes. As we all know, Rust has developed rapidly in recent years, but it also brings some new concepts, such as life cycle, etc., in addition, rust has no global state, or it is difficult to implement, and the compilation check is relatively strict, and the relative speed is relatively slow, which brings some difficulties to the implementation of web framework. Let's take a look at the implementation of these frameworks.

Rust Web framework classification

In the Rust Web framework, hyper, h3 and tiny-http belong to some of the underlying frameworks, such as hyper, many of which are developed based on it, and it is also an established framework in the Rust language; Rocket framework is relatively focused, and the author of the famous tokio implements Tower, which currently communicates more with warp, and may merge and everyone can continue to follow. The functions of iron, gotham, nickel, rouille and actix-web are relatively comprehensive, just like the whole system of Actix framework is huge, and many sub-frameworks are split below: web, http, net and so on.

Comparison of mainstream Web frameworks of Rust

Let's finally get down to business and pick out a few frameworks that have been used in our actual project for comparison. Of course, there may be some features of the framework that we have not dabbled in, and there are some inadequacies in the article that we welcome to correct.

Hyper

The first one to come out is hyper, which is characterized by high performance, and the stress test results given later are similar to those of actix-web; in addition, the Client component is implemented first, which makes it easy to write unit test verification; it is also mentioned earlier that many web frameworks are implemented based on hyper, which shows that the underlying encapsulation is good. But it also has some disadvantages:

There are relatively few functions on the application side of hyper, so it will cause many frameworks to continue to be encapsulated on his basis.

The author thinks that the implementation of routing through match block is an obvious disadvantage, such as the following example:

Async fn response_examples (req: Request,client: Client)-> Result {match (req.method (), req.uri (). Path ()) {(& Method::GET, "/ index.html") = > {Ok (Response::new (INDEX.into ()}, (& Method::GET "/ json_api") = > {api_get_response () .await} _ = > {Ok (Response::builder () .status (StatusCode::NOT_FOUND) .body (NOTFOUND.into ()) .unwrap ())}

This is a typical implementation of hyper, but match blocks in actual projects often need to turn a page or two when dealing with more complex processes, so it is relatively difficult to develop and review.

Actix-web

Actix-web is the known web framework to implement the actor model, developed by Microsoft engineer Nikolay, Azure uses more; Super fast is another advantage, in the web performance evaluation site, but suspected of deception, the following will explain how he does it; the bottom is based on tokio. The overall hierarchical structure is as follows:

Tokio & & futures-> actix-net/actix-rt-> actix-net/ other children crate-> actix-web

For actix as a whole, the features are still rich; 1. 0, released in June this year, further simplifies the actor module, service replaces handle, and a lot of simplified code.

Disadvantages: a large number of unsafe (figure below), resulting in developers often burst stack overflow bug;, which is also one of the reasons for his best performance

Another disadvantage is that the code quality is not high and changes frequently, at least in the web module, and the documentation and examples are not complete; for example, handle version 0.7 becomes service to version 1.0, and his encapsulated responder is also unstable. The following is compared with the implementation of rocket.

Rocket

Rocket is one of the mainstream Web frameworks of Rust, and the github project has 8.9k star. The http processing part of it is based on the Hyper mentioned earlier. According to the official data, it has the following three characteristics:

Type safety

It's easy to get started, making you more focused on your business.

Components are rich and almost all can be customized

Rocket from the author's experience: indeed get started very fast, developers from a variety of language backgrounds are relatively friendly; easy to expand, almost all his components can be customized, requestGuard, state, fairing can be customized; in addition, the document, example are very detailed, predefined many macros, very convenient; Rocket's disadvantages: performance will be slightly worse, will be given later stress test data. However, his async branch is also about to be released. It has been polished for several months. You can follow it.

Summary

Simply summarize a table (as shown below), and sum up: from everyone's attention, Rocket wins; Actix-web has more features, such as websocket; Rocket does the best in terms of peripheral support for use and application layer; so if you don't care too much about performance, it is recommended to choose Rocket. Next we will discuss Rocket in detail.

Rocket

Design principles of Rocket

First of all, let's take a look at the design principles of rocket, which other frameworks do not have, and their actual code implementation is also good. The specific principles are as follows:

Security, correctness, and developer experience are paramount.

All request handling information should be typed and self-contained

Decisions should not be forced

The author's understanding:

Security, correctness and developer experience are critical. This fully exploits the advantages of rust security and is friendly to developers of various languages. Later, we will talk about the two components request and guards.

All processed request information must be of a specified type. This also has some constraints on developers, such as having a deep feeling when using Responder components.

Restrictions should not be imposed. His templates, serialization, sessions and other components, almost all of the functions are optional plug-ins. For these, Rocket has an official library and support, which is completely free to choose and replace. So, Rocket is the perfect balance between freedom and constraint in the Rust Web framework. Let's expand on several important components in detail.

RequestGuards

RequestGuards is somewhat similar to the velidator of java's spring framework, which represents the type of arbitrary authentication policy, which is implemented through FromRequest. There is no limit on the number of RequestGuards. You can add it according to your own needs in actual use, or you can customize the Guards. For example:

# [get ("/")] fn index (param: isize, a: a, b: B, c: C)->. {.}

In the above examples, A, B, C are specific implementations, such as A verification auth,B verification count, C specific business verification, etc.; you can also use the guard that the framework has implemented, or define it yourself, the whole is still very flexible. Guard components also fulfill his first design principles: correctness and security.

Responder

Let's look directly at the definition of Responder:

Pub trait Responder {/ Returns `Ok`if a `Response` could be generated successfully. Otherwise, / returns an `Err`with a failing `Status`. / The `request` parameter is the `Request` that this `Responder` is / responding to. / When using Rocket's code generation, if an `Ok (Response) `is returned, / the response will be written out to the client. If an `Err (Status) `is / returned, the error catcher for the given status is retrieved and called / to generate a final error response, which is then written out to the / client. Fn respond_to (self, request: & Request)-> response::Result;}

The author looked through the code record of this trait and found that the design has been confirmed since the beginning of 16 years. It is very stable and has not been updated since. The Result returned by respond_to, which he encapsulates, is either OK or a status of Err. In addition, common types (str, String, [U8], File, Option, Status) are built-in, which basically cover most business scenarios. If not, you can also implement custom responder. This reflects his second design principle: type constraint. Unlike other frameworks, such as Actix-web, which also have responder, it is only recently that the version has stabilized. What if you want to customize it as follows? This is an example of customization:

Impl Responder for Person {fn respond_to (self, _: & Request)-> response::Result {Response::build () .sized _ body (Cursor::new (format! ("{}: {}", self.name, self.age)) .raw _ header ("X-Person-Name", self.name) .header (ContentType::new ("application") "x-person") .ok ()} # [get ("/ person")] fn person ()-> Person {Person {name: "a" .to _ string (), age: 20}}

This is a custom responder that returns a Person object directly; you can also add the processing of err; it still looks relatively simple. We can compare the implementation of Actix-web 's responder:

Pub trait Responder {/ The associated error which can be returned. Type Error: Into; / The future response value. Type Future: Future; / Convert itself to `AsyncResult` or `Error`. Fn respond_to (self, req: & HttpRequest)-> Self::Future; fn with_status (self, status: StatusCode)-> CustomResponder where Self: Sized, {CustomResponder::new (self). With_status (status)} fn with_header (self, key: K, value: v)-> CustomResponder... ... }

Actix-web did not have this component until March 19, and status,header was added later; it is much more complicated to implement.

State

Let's take a look at the State component of Rocket, which is also the embodiment of the last principle. Give a direct example:

Use rocket::State; use rocket::response::content; struct HitCount (AtomicUsize); # [get ("/")] fn index (hit_count: State)-> content::Html {hit_count.0.fetch_add (1, Ordering::Relaxed); let msg = "Your visit has been recorded!"; let count = format! ("Visits: {}", count (hit_count)) Content::Html (format! ("{} {}", msg, count))} # [get ("/ count")] fn count (hit_count: State)-> String {hit_count.0.load (Ordering::Relaxed). To_string ()} fn rocket ()-> rocket::Rocket {rocket::ignite () .mount ("/", routes! [index) Count]) .manage (HitCount (AtomicUsize::new (0)}

This is a simple implementation of a counter, which is injected into handle through state, adding 1 for each visit; you can also get the current count through the / cout interface; these two interfaces are stateless, but count is global, which is the charm of state; of course, state can do a lot of things, in addition to the built-in implementation of Request-local state, similar to thread-local can do link tracking

Fairing

Rocket also has a Fairing component, which, combined with the state component mentioned above, can realize some customization of request and response when the application is started or attach of state. For example, custom filter, log and other plug-ins can be implemented.

# [derive (Default)] struct Counter {get: AtomicUsize, post: AtomicUsize,} impl Fairing for Counter {fn on_request (& self, request: & mut Request, _: & Data) {… ... } fn on_response (& self, request: Request, response: mut Response) {… ... }} fn rocket ()-> rocket::Rocket {rocket::ignite () .mount ("/", routes! [... ,...]) Counter::default ())... ... }

This is a separate counting function according to the request method, and you can also implement event handling for Counter's attach; but unlike filter, Fairing is more generic. Its characteristics are as follows:

The lifecycle of mounting in Request

Cannot terminate or respond directly to Request

Unsolicited data cannot be injected into Request

You can check or modify the configuration

Only attach can trigger.

Order is important.

Fairing can be used in some dynamic configuration scenarios or complex configuration scenarios in a variety of environments, and the official intimate built-in Adhoc implementation makes it easy for developers to implement it quickly.

At this point, I have finished talking about the features of Rocket, so I suggest you choose your own appropriate framework according to your actual needs.

Pressure test data reference

Finally, we give the results of the pressure test done before:

Thank you for your reading, the above is the content of "what is the Rust Web framework?" after the study of this article, I believe you have a deeper understanding of what the Rust Web framework has, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report