Skip to content

Commit c2ae07d

Browse files
committed
Add a CORS header injection Interceptor
It an option `:allow` option to define which origins are allowed. This may be a static string or a function which will be passed the current `req` and `stream` structs to choose what to allow.
1 parent c39c834 commit c2ae07d

File tree

1 file changed

+23
-0
lines changed
  • lib/grpc/server/interceptors

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
defmodule GRPC.Server.Interceptors.CORS do
2+
@behaviour GRPC.Server.Interceptor
3+
@impl true
4+
def init(opts) do
5+
case Keyword.get(opts, :allow) do
6+
fun when is_function(fun, 2) -> fun
7+
static when is_binary(static) -> fn _, _ -> static end
8+
_ -> fn _, _ -> "*" end
9+
end
10+
end
11+
12+
@impl true
13+
def call(req, stream, next, allowed_fn) do
14+
if stream.client_type != :grpc do
15+
stream.adapter.set_headers(stream.payload, %{
16+
"access-control-allow-origin" => allowed_fn.(req, stream),
17+
"access-control-allow-headers" => "content-type, x-grpc-web, x-user-agent, x-api-key"
18+
})
19+
end
20+
21+
next.(req, stream)
22+
end
23+
end

0 commit comments

Comments
 (0)