Reputation: 1502
I'm working on embedding actix-web into a binding library. I would like to declare a HttpServer
within a struct so that I can easily call .start()
and .system_exit()
. From my very basic reading of the source code it's already implemented as a struct with two dependencies: <H, F>
. It also comes with a factory to instantiate itself.
If I'm understanding this correctly, then I would have to implement the HttpServer
as a dependency in my new struct and add my own characteristics within it. My previous thought was to create a new struct and just declare HttpServer
as a property within it. That seemed troublesome with the generics that needed to be declared within it.
What I've come up with so far is:
struct CustomServer<T> {
srv: T,
}
impl<T> CustomServer<T>
where
T: HttpServer,
{
fn init() {
self.srv = HttpServer::new(|| App /* etc. */)
}
}
I'm not sure if I'm grasping at straws or in the right direction.
The question is: how should/can I go about defining a struct that has HttpServer and it's functions accessible in my struct?
Upvotes: 3
Views: 1233
Reputation: 3875
HttpServer
is a generic struct, not a trait (so “T: HttpServer
” doesn’t make sense).
You can either make a generic struct that contains a totally arbitrary instantiation of HttpServer
(this is likely not very useful to you):
struct CustomServer<H: IntoHttpHandler + 'static, F: Fn() -> H + Send + Clone + 'static> {
srv: HttpServer<H, F>,
}
impl<H: IntoHttpHandler + 'static, F: Fn() -> H + Send + Clone + 'static> CustomServer<H, F> {
fn new(factory: F) -> CustomServer<H, F> {
CustomServer {
srv: HttpServer::new(factory),
}
}
}
or a concrete struct that contains a particular kind of HttpServer
(I’m guessing this is what you’ll want, though it’s hard to say without details of your use case):
struct CustomServer {
srv: HttpServer<App, fn() -> App>,
}
impl CustomServer {
fn new() -> CustomServer {
CustomServer {
srv: HttpServer::new(|| App),
}
}
}
There are also many points in between (e.g. specialize H
but not F
, or specialize slightly based on other generic parameters), depending on what you’re trying to do.
Upvotes: 2