import { suggestResponseType } from "https://deno.land/x/ayonli_jsext@v0.9.72/http/util.ts";
Gets the suggested response type for the request.
This function checks the Accept
or the Content-Type
header of the request,
or the request method, or other factors to determine the most suitable
response type for the client.
For example, when requesting an article which is stored in markdown, the server can respond an HTML page for the browser, a plain text for the terminal, or a JSON object for the API client.
This function returns the following response types:
text
: plain text content (default)html
: an HTML pagexml
: an XML documentjson
: a JSON objectstream
: text stream or binary stream, depending on the use casenone
: no content should be sent, such as for aHEAD
request
Examples
Example 1
Example 1
import { suggestResponseType } from "@ayonli/jsext/http";
export default {
async fetch(req: Request) {
const type = suggestResponseType(req);
if (type === "text") {
return new Response("Hello, World!");
} else if (type === "html") {
return new Response("<h1>Hello, World!</h1>", {
headers: { "Content-Type": "text/html" },
});
} else if (type === "xml") {
return new Response("<xml><message>Hello, World!</message></xml>", {
headers: { "Content-Type": "application/xml" },
});
} else if (type === "json") {
return new Response(JSON.stringify({ message: "Hello, World!" }), {
headers: { "Content-Type": "application/json" },
});
} else {
return new Response(null, { status: 204 });
}
}
}
Parameters
req: Request