Skip to content

Instantly share code, notes, and snippets.

@tobias-
Last active August 30, 2019 07:57
Show Gist options
  • Save tobias-/cbdc441872d2256b1d7a318b54ae057e to your computer and use it in GitHub Desktop.
Save tobias-/cbdc441872d2256b1d7a318b54ae057e to your computer and use it in GitHub Desktop.
import com.linecorp.armeria.common.HttpMethod
import com.linecorp.armeria.common.HttpService
import com.linecorp.armeria.server.SimpleDecoratingHttpService
import com.linecorp.armeria.server.Service
import com.linecorp.armeria.server.cors.CorsService
import com.linecorp.armeria.server.cors.CorsServiceBuilder
import org.kodein.di.Kodein
import org.kodein.di.direct
import org.kodein.di.generic.instance
import java.util.function.Function
interface GrpcDecorator<T> : Function<HttpService, SimpleDecoratingHttpService>
@Suppress("UNCHECKED_CAST")
class GrpcWebCors(kodein: Kodein) :
GrpcDecorator<CorsService>,
Function<HttpService, SimpleDecoratingHttpService>
by
CorsServiceBuilder
.forOrigins(
"https://example.com"
)
.allowCredentials()
.allowNullOrigin()
.allowRequestMethods(HttpMethod.POST, HttpMethod.GET)
.allowRequestHeaders(
"authorization",
"content-type",
"x-grpc-web"
)
.exposeHeaders(
"grpc-message",
"grpc-status",
"x-server-version"
)
.newDecorator() as Function<HttpService, SimpleDecoratingHttpService>
@tobias-
Copy link
Author

tobias- commented Aug 30, 2019

Short description of what happens here:

  1. The GrpcDecorator is so that DependencyInjection can pick up and add them to the GrpcServices.
  2. the by keyword creates a delegate class and uses what comes to the right as the delegate. i.e. all (one) method of Function is delegated to the CorsServiceBuilder.newDecorator()

Used like:

val grpcDecorators: List<GrpcDecorator<*>> by kodein.allInstances()
...
val withDecorators = grpcDecorators
    .fold(grpcService) { service, decorator ->
        service.decorate(decorator)
    }

Revision #1 is generics-hell, but works fine.
Second revision throws:

java.lang.ClassCastException: class com.linecorp.armeria.server.FunctionalDecoratingService cannot be cast to class com.linecorp.armeria.server.HttpService (com.linecorp.armeria.server.FunctionalDecoratingService and com.linecorp.armeria.server.HttpService are in unnamed module of loader 'app')

@tobias-
Copy link
Author

tobias- commented Aug 30, 2019

Kodein is the DI framework

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment