Send Headers Automatically

预计阅读时间: 2 分钟

This feature adds a default set of headers to HTTP responses. The list of headers is customizable, and the Date header is cached to avoid building complex strings on each response.

本特性在 io.ktor.features.DefaultHeaders 类中定义,无需任何额外构件。

Usage

fun Application.main() {
  ...
  install(DefaultHeaders)
  ...
}

This will add Date and Server headers to each HTTP response.

Configuration

  • header(name, value) will add another header to the list of default headers
fun Application.main() {
  ...
  install(DefaultHeaders) {
    header("X-Developer", "John Doe") // will send this header with each response
  }
  ...
}
  • default Server header can be overriden by specifying your custom header:
fun Application.main() {
  ...
  install(DefaultHeaders) {
    header(HttpHeaders.Server, "Konstructor") 
  }
  ...
}
  • The default Date header cannot be overridden. If you need to override it, do not install the DefaultHeaders feature and instead intercept the call manually