atuttle / Taffy

:candy: The REST Web Service framework for ColdFusion and Lucee
http://taffy.io
Other
226 stars 118 forks source link

How to return plain text/HTML fragment (not as JSON) #430

Closed JamoCA closed 1 year ago

JamoCA commented 2 years ago

Some sample CFML on a recent blog entry from Ben Nadel regarding "Extending A ColdFusion Session On A Long-Lived Page" used charsetDecode to return JSON using CFContent in cfscript syntax.

cfcontent(
   type = "application/json; charset=utf-8",
   variable = charsetDecode( serializeJson({ "sessionID": session.id }), "utf-8" )
);

In the past, I was struggling with how to return plain HTML using Taffy without writing a new serializer or using writeOutput w/cfabort. I reviewed all the Taffy examples and know how to return files, but didn't know how to return plain HTML. Ben's code provided me with some new hope and I was able to finally figure it out.

On one of our API endpoints, I wanted to add an option to return plain HTML when adding an returnHtml boolean parameter. This solution worked for me. Is this the best solution or does another exist? Also, could something like this be added to the base serializer? Thanks.

if (arguments.returnHtml){
    htmlFile = charsetDecode(javacast("string", myHtml), "utf-8");  //binary encoded HTML
    return streamBinary(htmlFile).withStatus(200).withMime("text/html");
}
bennadel commented 2 years ago

Yeah, the cfcontent tag internally aborts the request. I think it actually does three things:

So, nothing after a CFContent tag actually gets executed.

atuttle commented 2 years ago

A long time ago the representationOf/rep methods supported a 2nd argument for specifying a format or serializer for just that one request. It was never utilized by anyone. @JamoCA your mention of wanting it for one endpoint made me remember that. Not sure if it would be of use here. I'm pretty sure it's been removed for a long time now, though.

I would say that if your current approach with streamBinary is working, then it seems reasonable to me.