在Compojure中提供静态favicon文件

时间:2015-07-28 13:03:45

标签: clojure compojure

根据Compojure

  

默认情况下,Compojure不提供静态文件,也不提供   当没有路线匹配时自动处理404s。

为了解决这个问题,我们必须设置这些Public Vars

  • files
  • 未找到
  • 资源

这就是我们目前的设定方式:

(defroutes app-routes
  (route/files "/" {:root "path/to/public"})
  (route/resources "/")
  (route/not-found "Not Found"))

当通过Web浏览器访问大多数静态文件时,它按预期工作。

e.g。

http://localhost:3000/img/icon.png

但问题是,它不适用于favicon文件。

e.g。

http://localhost:3000/img/favicon.ico

它将此视为一个不同的调用,它应该作为静态文件。

对我运行的CURL的回复:

* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /img/favicon.ico HTTP/1.1
> User-Agent: curl/7.38.0
> Host: localhost:3000
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Tue, 28 Jul 2015 19:05:24 GMT
< Last-Modified: Thu, 28 May 2015 14:51:16 +0000
< Content-Length: 1106
< Content-Type: image/x-icon
* Server Jetty(7.6.13.v20130916) is not blacklisted
< Server: Jetty(7.6.13.v20130916)

2 个答案:

答案 0 :(得分:3)

filesresourcesnot-found是函数,而不是您设置的变量。当您致电(route/files "/" {:root "path/to/public"})时,会返回将“/”下的网址解析为“path / to / public”下的静态文件的路由。

defroutes定义了一系列路线。这些路由按列出的顺序进行尝试,直到第一个返回响应。

如果您在其他路线之前添加路线(GET "/:slug" [* :as req slug] (search req slug)),则此新路线将处理除“/”以外的任何网址 - 包括favicon请求。另一方面,如果您在not-found路线之前添加它,那么它应该可以工作。

此外,如果没有与请求匹配的静态文件,则files路由将失败,并尝试下一个路由。因此,您还应检查favicon.ico是否确实存在且位于img子目录中。

答案 1 :(得分:0)

嗯...

这对我有用(无论您在哪里定义/声明路线):

在名称空间部分:

fig = plt.figure(figsize=(9, 6))

count = 0
for i in range(4):
    for j in range(4):
        count += 1
        if i >= j:
            ax = fig.add_subplot(4, 4, count)
            ax.text(0.5, 0.5, str(count))

低于(至少高于(def app)之上:

            [ring.util.response :refer [resource-response]]

然后进入:

(defn wrap-return-favicon [handler]
  (fn [req]
    (if (= [:get "/favicon.ico"] [(:request-method req) (:uri req)])
      (resource-response "favicon.ico" {:root "public/img"})
      (handler req))))
相关问题