I'm trying to write a plugin that alters HTML file...
# ktor
m
I'm trying to write a plugin that alters HTML files served by Ktor. In
onCallRespond
/
transformBody
, the
data
argument I get is
Any
. When printing its type when a static HTML file is served, I get a
io.ktor.server.http.content.PreCompressedResponse
(I don't have compression configured on this server). Is there a way to get the actual body?
I'm also not too sure how to get the served file type - how to determined whether it's an HTML file or not. I could do without that though.
a
You can call the
readFrom()
method of the
PreCompressedResponse
object to get a
ByteReadChannel
which can be used to read a content. A content of a file isn’t actually compressed.
m
That's what I just found - I had to dig a bit as as far as I can tell,
PreCompressedResponse
isn't in the documentation. I also have to cast it, as it comes out as an
Any
, but I can live with that.
I figured out how to read the content, but how can I write, or replace the content? Just returning a String from
transformBody
results in a 406 Not Acceptable
I take that back - returning a String returns it as plain text
I need to set the content type somehow I guess
a
Doesn’t the
contentType
property of
PreCompressedResponse
contain a value for the
Content-Type
header?
m
Err sorry you're right, I was so focused on reading the channel that I didn't look at the other
OutgoingContent.ReadChannelContent
attributes. It does have the
Content-Type
set to
text/html
, which is great. I can filter out HTML files easily. Now is there a canonical way to replace the response body by conserving the headers etc?
(I'm actually a bit surprised that
transformBody
doesn't do just that)
a
Should the
Content-Length
header be modified too?
m
I assume it would need to be modified indeed, but returning a
String
from
transformBody
seems to override every header regardless - Firefox receives a
text/plain
with the proper
Content-Length
I assume I need to construct some sort of response object, but I really don't know where to start looking at, the documentation around plugins seems to be a bit scarce
Oh, actually, I guess any kind of
OutgoingContent
subclass would do...
Yep, using a
WriterContent
setting both the
body
and
contentType
works just fine
Thanks a lot!