I am using SBCL, Emacs, and Slime. Moreover, I am using the library Dexador. Thus, I can do HTTP requests. Some of them will return JSON:
CL-USER> (dex:get "http://ip.jsontest.com/")
"{\"ip\": \"179.878.248.207\"}
Others will return HTML:
(dex:get "https://ambrevar.xyz/")
"<!DOCTYPE html>
<html lang=\"en\">
<head>
<!-- 2021-12-29 -->
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<title>‎</title>
<meta name=\"generator\" content=\"Org mode\">
<meta name=\"author\" content=\"root\">
<link rel=\"stylesheet\" type=\"text/css\" href=\"../dark.css\">
<link rel=\"icon\" type=\"image/x-icon\" href=\"../logo.png\">
</head>
<body>
<div id=\"content\">
<div id=\"outline-container-org4051da4\" class=\"outline-2\">
<h2 id=\"org4051da4\">Contact</h2>
<div class=\"outline-text-2\" id=\"text-org4051da4\">
<ul class=\"org-ul\">
<li>Email: <a href=\"mailto:mail@ambrevar.xyz\">mail@ambrevar.xyz</a></li>
<li>PGP: <a href=\"ambrevar.asc\">0x9BDCF497A4BBCC7F</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
"
After storing the result inside variables with:
CL-USER> (defparameter html-response (dex:get "https://ambrevar.xyz/"))
HTML-RESPONSE
CL-USER> (defparameter json-response (dex:get "http://ip.jsontest.com/"))
JSON-RESPONSE
I would like to create a function to check if the output is JSON or HTML. Hence, I did this function:
(defun html-or-json (response)
"Check it the server response is HTML or JSON data."
(cond ((null response) nil)
((equal (subseq response 0 1) "<") "html")
(t "json")))
It works:
CL-USER> (html-or-json json-response)
"json"
CL-USER> (html-or-json html-response)
"html"
However, my solutions seems ugly to me. Initially, I tried using handle-case and serializing the answer as JSON. If it worked, it would be a JSON. If it failed, the function would consider the object as HTML. But things did not go well since I am not proficient with handle-case syntax.
Can you think of an alternative to achieve this goal? Maybe using handle-case?