Last active
January 30, 2018 11:30
-
-
Save AlejandroRivera/713207c8e4b3699c6383c2ce3d706859 to your computer and use it in GitHub Desktop.
Using Play's MVC RequestHeader info in a WS Client filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.inject.{Inject, Singleton} | |
import play.api.libs.ws.{WSClient, WSRequest, WSRequestFilter} | |
@Singleton | |
class MyWsClient @Inject()(wsClient: WSClient, | |
filters: java.util.Set[WSRequestFilter] ) extends WSClient { | |
override def underlying[T]: T = wsClient.asInstanceOf[T] | |
override def url (url: String): WSRequest = { | |
val request: WSRequest = wsClient.url(url) | |
filters.forEach(filter => request.withRequestFilter(filter)) | |
request | |
} | |
override def close (): Unit = wsClient.close () | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Singleton | |
class TracerForwarderWsClientFilter @Inject()(configuration: Config) | |
(implicit parentRequest: RequestHeader) extends WSRequestFilter { | |
val someValue = configuration.getInt("foobar") | |
override def apply(executor: WSRequestExecutor): WSRequestExecutor = { | |
(request: StandaloneWSRequest) => { | |
request.addHttpHeaders(("x-tracer-id", parentRequest.headers.get("x-tracer-id").getOrElse("n/a"))) | |
executor.apply(request) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.inject.AbstractModule | |
import com.google.inject.multibindings.Multibinder | |
import play.api.libs.ws.WSRequestFilter | |
class WsClientFiltersModule extends AbstractModule { | |
override protected def configure(): Unit = { | |
val requestFilterMultibinder: Multibinder[WSRequestFilter] = Multibinder.newSetBinder(binder, classOf[WSRequestFilter]) | |
requestFilterMultibinder.addBinding().to(classOf[TracerForwarderWsClientFilter]).asEagerSingleton() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment