icerockdev / moko-network

Network components with codegeneration of rest api for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev
Apache License 2.0
151 stars 29 forks source link

Allow UserAgent feature to have a dynamic source of its value #176

Closed dalewking closed 2 years ago

dalewking commented 2 years ago

I have a case where the UserAgent can change depending on server, so needed it to be dynamic and not a fixed string. Here is the class I came up with in case it is useful to others:

class DynamicUserAgent(val agentProvider: () -> String?) {
    class Config(var agentProvider: () -> String? = { null })

    companion object Feature : HttpClientFeature<Config, DynamicUserAgent> {
        override val key: AttributeKey<DynamicUserAgent> = AttributeKey("DynamicUserAgent")

        override fun prepare(block: Config.() -> Unit): DynamicUserAgent =
            DynamicUserAgent(Config().apply(block).agentProvider)

        override fun install(feature: DynamicUserAgent, scope: HttpClient) {
            scope.requestPipeline.intercept(HttpRequestPipeline.State) {
                feature.agentProvider()
                    ?.let { context.header(HttpHeaders.UserAgent, it) }
            }
        }
    }
}
Alex009 commented 2 years ago

will be available in 0.18.0