Carlos
Carlos

Reputation: 1133

How to add a header to a Vapor response (Cache-Control)

I have a controller using a get handler that returns a Future<Content>. I would like to add a header to the response (Cache-Control to be specific). I was thinking that it should be easy but I'm not finding how to do it. Which would be the way to add a header in this case? When we are working with Content instead of Response

Upvotes: 4

Views: 914

Answers (2)

DIV
DIV

Reputation: 263

Mike's answer is spot on... This worked for me. As a further reference, I used a value to extend the cache for 1 day on all public caches.

req.headers.add(name: .cacheControl, value: "public, max-age=86400")

Upvotes: 3

imike
imike

Reputation: 5656

To solve the problem you could write your endpoint like this

struct Something: Content {
    let text: String
}
router.get("customresponse") { req -> Future<Response> in
    return try Something(text: "Hello world").encode(for: req).map { response in
        response.http.headers.add(name: .cacheControl, value: "something")
        return response
    }
}

Upvotes: 9

Related Questions