0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

KtorでAcceptやContent-Typeヘッダーに応じてルーティングする

Posted at

ActivityPub実装作っていて欲しくなったので作りました。

Acceptヘッダーを見て判断

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.routing.*

class AcceptContentTypeRouteSelector(private vararg val contentType: ContentType) : RouteSelector() {
    override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {

        val requestContentType =
            ContentType.parse(context.call.request.accept() ?: return RouteSelectorEvaluation.FailedParameter)
        return if (contentType.any { contentType -> contentType.match(requestContentType) }) {
            RouteSelectorEvaluation.Constant
        } else {
            RouteSelectorEvaluation.FailedParameter
        }
    }

}

ContentTypeで判断

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.routing.*

class ContentTypeRouteSelector(private vararg val contentType: ContentType) : RouteSelector() {
    override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {

        val requestContentType = context.call.request.contentType() ?: return RouteSelectorEvaluation.FailedParameter
        return if (contentType.any { contentType -> contentType.match(requestContentType) }) {
            RouteSelectorEvaluation.Constant
        } else {
            RouteSelectorEvaluation.FailedParameter
        }
    }

}

使い方

この例の場合 /jsonにAcceptヘッダーがapplication/jsonでGETリクエストが来たときにマッチします。

fun Application.routing(){
    routing {
        get("/json"){
            createChild(AcceptContentTypeRouteSelector(ContentType.Application.Json)).handle {
            //ここからは通常のルーティング処理と同じ
                call.respond(HttpStatusCode.Ok)
            }
        }
    }
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?