Skip to content

Commit

Permalink
Add server side middleware support
Browse files Browse the repository at this point in the history
  • Loading branch information
vonmixer committed Nov 30, 2017
1 parent 89bc5e6 commit 8f13fb1
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 73 deletions.
5 changes: 5 additions & 0 deletions doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,12 @@ On the server side, a message that is sent to the client can be compressed
by applying `grpc:set_compression/2` on the stream, similar to the way
metadata can be added using `grpc:set_headers/2` or `grpc:set_trailers/2`.

## Server Middleware

You can implement middleware as described in https://ninenines.eu/docs/en/cowboy/1.0/guide/middlewares/. The list of middlewares in order of execution will then need to be specified in the `middlewares` option when starting the server. The list must include `cowboy_router` and `cowboy_handler`.

TODO:
- Timeout.
- Description and improvement of the actual implementation of error
handling.
- Client side middleware support
10 changes: 10 additions & 0 deletions examples/route_guide/server/route_guide_logging_middleware.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
%% Middleware example that logs to disk
-module(route_guide_middleware).
-behaviour(cowboy_middleware).

-export([execute/2]).

execute(Req, Env) ->
LoggingData = "here are some logs",
ok = file:write_file("route_guide_middleware_log", LoggingData),
{ok, Req, Env}.
13 changes: 12 additions & 1 deletion src/grpc_server.erl
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
start(Name, Transport, Port, Services, Options) ->
{ok, _Started} = application:ensure_all_started(grpc),
AuthFun = get_authfun(Transport, Options),
Middlewares = get_middlewares(Options),
%% All requests are dispatched to this same module (?MODULE),
%% which means that `init/2` below will be called for each
%% request.
Expand All @@ -57,7 +58,8 @@ start(Name, Transport, Port, Services, Options) ->
ProtocolOpts = #{env => #{dispatch => Dispatch},
%% inactivity_timeout => infinity,
stream_handlers => [grpc_stream_handler,
cowboy_stream_h]},
cowboy_stream_h],
middlewares => Middlewares},
case Transport of
tcp ->
cowboy:start_clear(Name, [{port, Port}], ProtocolOpts);
Expand Down Expand Up @@ -146,6 +148,15 @@ get_authfun(ssl, Options) ->
get_authfun(_, _) ->
undefined.

get_middlewares(Options) ->
case proplists:get_value(middlewares, Options) of
undefined ->
%% defaulting to default cowboy middlewares
[cowboy_router, cowboy_handler];
Middlewares ->
Middlewares
end.

authenticate(Req, #{auth_fun := AuthFun}) when is_function(AuthFun) ->
case cowboy_req:cert(Req) of
undefined ->
Expand Down
Loading

0 comments on commit 8f13fb1

Please sign in to comment.