apptreesoftware / protoc-gen-twirp_dart

A twirp protoc generator for Dart
MIT License
30 stars 19 forks source link

To set request header #3

Closed n04ln closed 5 years ago

n04ln commented 5 years ago

Currently, request is set only Content-Type header. So, I suggest a solution to set other header. (This solution is inspired by gRPC)

  1. define CallOptions class (like following code) in https://github.com/apptreesoftware/twirp_dart_core

    class CallOptions {
    Map<String, String> headers;
    CallOptions() {
        headers = new Map<String, String>();
    }
    void setHeader(String key, String value) {
        headers[key] = value;
    }
    }
  2. call rpc method with CallOptions

    // define by auto-generated file
    Future<UserProfile>getMyProfile(Empty empty, {CallOptions opts}) async {
    ...
    if (opts != null) {
        opts.headers.forEach((String k, String v) {
            request.headers[k] = v;
        });
    }
    ...
    }
    // call
    var opts = new CallOptions();
    opts.setHeader("Authorization", "Bearer ${token}");
    var res = service.getMyProfile(new Empty(), opts: opts);

I implemented in https://github.com/NoahOrberg/protoc-gen-twirp_dart/tree/n/hotfix/inner-class. (but, CallOptions definition is included auto-generated file, and don't mention this branch name..)

matthewtsmith commented 5 years ago

@NoahOrberg This is already possible. The Default<ServiceName> method takes a Requestor. It is not a required param but if you pass it it allows you to customize the request. A Requestor allows you to supply number of Middleware. The Middleware gives you hooks for modifying the request before it goes out.

n04ln commented 5 years ago

Thanks for your reply.

It worked!

Thank you.