joaotavora / snooze

Common Lisp RESTful web development
207 stars 22 forks source link

How to Serve Javascript #12

Closed skidd0 closed 6 years ago

skidd0 commented 6 years ago

I have a file "scripts.js" in my directory that I'm trying to include in a spinneret template. I can't figure out how to serve this file with snooze.

I have tried:

(defroute scripts.js (:get :text/*)
  (uiop:read-file-lines "scripts.js")
  (payload-as-string))

which produces a 404. and,

(defroute "scripts.js" ... )

which SBCL tells me is an 'illegal generic function name'.

I might try baking the script into my HTML template with spinneret next, but I'm wondering if there's an easy fix I'm not seeing.

Also, you mention that we can email you in the README, but I could not find your email address anywhere, so I have opened this issue.

joaotavora commented 6 years ago

which produces a 404

This produces a 404 because snooze is looking for a route called scripts that serves javascript. And it does that because, that is the default behaviour of *uri-content-types-function*. If you modify your route to

(defroute scripts (:get :application/x-javascript) ...)

You should get it over a HTTP request for /scripts.js that accepts only javascript.

To get rid of this extension-as-content-type behaviour, customize *uri-content-types-function*

(setq *uri-content-types-function* nil)

(uiop:read-file-lines "scripts.js") (payload-as-string))

This body for a route makes no sense. First you are reading a file into a list of strings and immediately discarding that value. Then you are returning the request's payload as the response, but for a GET request the payload is usually empty. You would need to return a strings obtained by concatenating all the lines of the uiop:read-file-lines call.

But, by far the easiest way to serve static files in snooze is not to go through snooze at all. If you are using hunchentoot, hunchentoot:create-folder-dispatcher-and-handler is what you want. If you are using clack or something else, ask the developer of that web server, I'm sure there's an easy way to serve static content.

skidd0 commented 6 years ago

Thank you for the quick response.

I looked into the create-folder-dispatcher-and-handler and copied the example you have in the demo folder. This works well, thank you.

joaotavora commented 6 years ago

Thank you for the quick response.

You're welcome, and btw you can find my email address in the commits or by joining my username with a very popular mail provider. Issues are good places for public discussion such as this, though.