pub trait Plugin:
Any
+ Sized
+ Send
+ Sync {
const CODE: &'static str;
const MONO: bool = false;
// Required methods
fn call(
&self,
req: SgRequest,
inner: Inner,
) -> impl Future<Output = Result<SgResponse, BoxError>> + Send;
fn create(plugin_config: PluginConfig) -> Result<Self, BoxError>;
// Provided methods
fn meta() -> PluginMetaData { ... }
fn create_by_spec(
spec: JsonValue,
name: PluginInstanceName,
) -> Result<Self, BoxError> { ... }
fn register(repo: &PluginRepository) { ... }
}
Expand description
§Plugin Trait
It’s a easy way to define a plugin through this trait.
You should give a unique code
for the plugin,
and implement the call
function and the create
function.
§Example
In the follow example, we add a server header for each response.
pub struct ServerHeaderPlugin {
header_value: String,
}
impl Plugin for ServerHeaderPlugin {
const CODE: &'static str = "server-header";
async fn call(&self, req: SgRequest, inner: Inner) -> Result<SgResponse, BoxError> {
let mut resp = inner.call(req).await;
resp.headers_mut().insert("server", self.header_value.parse()?);
Ok(resp)
}
fn create(plugin_config: PluginConfig) -> Result<Self, BoxError> {
let Some(header_value) = plugin_config.spec.get("header_value") else {
return Err("missing header_value".into())
};
Ok(Self {
header_value: header_value.as_str().unwrap_or("spacegate").to_string(),
})
}
}
Required Associated Constants§
Provided Associated Constants§
Required Methods§
Sourcefn call(
&self,
req: SgRequest,
inner: Inner,
) -> impl Future<Output = Result<SgResponse, BoxError>> + Send
fn call( &self, req: SgRequest, inner: Inner, ) -> impl Future<Output = Result<SgResponse, BoxError>> + Send
This function will be called when the plugin is invoked.
The error will be wrapped with a response with status code 500, and the error message will be response’s body.
If you want to return a custom response, wrap it with Ok
and return it.
If you want to return a error response with other status code, use PluginError::new
to create a error response, and wrap
it with Ok
.
fn create(plugin_config: PluginConfig) -> Result<Self, BoxError>
Provided Methods§
fn meta() -> PluginMetaData
fn create_by_spec( spec: JsonValue, name: PluginInstanceName, ) -> Result<Self, BoxError>
Sourcefn register(repo: &PluginRepository)
fn register(repo: &PluginRepository)
Register the plugin to the repository.
You can also register axum server route here.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.