Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] how to set header when a request leaves the grpc server #2056

Open
liubocflt opened this issue Nov 18, 2024 · 2 comments
Open

[question] how to set header when a request leaves the grpc server #2056

liubocflt opened this issue Nov 18, 2024 · 2 comments

Comments

@liubocflt
Copy link

liubocflt commented Nov 18, 2024

Hi devs,

Thanks a lot for developing tonic for rust grpc.

I'm looking for a solution of tonic to set header in an interceptor when a request leaves the grpc server, is there a helper for this to do so?

In golang, it can be written as

func fooInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    startTime := time.Now()
    err := handler(ctx, req)
    // elapsedTime := time.Since(startTime).Nanoseconds()
    // set header
    return err
}
@imotai
Copy link

imotai commented Nov 20, 2024

Maybe the following answer can help you.

  1. add the meta to the response
use tonic::{Request, Response, Status};
use std::time::Instant;

async fn foo_interceptor<S>(
    mut req: Request<S>,
    next: tonic::service::Interceptor,
) -> Result<Response<S>, Status> {
    let start = Instant::now();
    
    // Handle the request
    let mut response = next.call(req).await?;
    
    // Add custom headers to response
    response.metadata_mut()
        .insert("x-elapsed-time", elapsed.as_nanos().to_string().parse().unwrap());

    Ok(response)
}
  1. add the inteceptor to the server
Server::builder()
    .add_service(
        ServiceBuilder::new()
            .intercept(foo_interceptor)
            .service(your_service)
    )
    .serve(addr)
    .await?;

@liubocflt
Copy link
Author

liubocflt commented Nov 23, 2024

@imotai Thanks for your suggestions, unfortunately, I was not able to make it work with next: tonic::service::Interceptor.

I did it successfully with the example here, It's cumbersome to do it this way though.
https://github.com/hyperium/tonic/blob/master/examples/src/tower/server.rs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants