首页 > 解决方案 > Clojure:如何为服务器设置特定的 url?

问题描述

我是 clojure 的新手,我正在尝试使用它来托管具有特定 url 的服务器。

在网上做了一些研究,我得到了以下信息。

(ns rest-demo.core
  (:require [org.httpkit.server :as server]
            [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.middleware.defaults :refer :all]
            [clojure.string :as str]
            [clojure.data.json :as json])
  (:gen-class))

(defn hello-name
  [req]
  {:status  200
   :headers {"Content-Type" "text/html"}
   :body (str "Hello " (:name (:params req)))})

(defroutes app-routes
  (GET "/hello" [] hello-name)
  (route/not-found "Error, page not found!"))

(defn -main
  "This is our main entry point"
  [& args]
  (let [port (Integer/parseInt (or (System/getenv "PORT") "3000"))]
    ; Run the server with Ring.defaults middleware
    (server/run-server (wrap-defaults #'app-routes site-defaults) {:port port})))

运行lein run和访问127.0.0.1:3000/hello我可以访问 API。

我将如何使用我选择的 url 来托管它?

提前致谢!

标签: restweb-servicesclojure

解决方案


一个 URL* 由几个部分组成,其中最重要的两个是

  1. 托管它的计算机的主机名
  2. 特定页面的路径。

看起来你已经照顾了#2。为了解决#1,您可以采取两种方法:

  1. 在互联网上找到一个好地方来托管您的程序。像 Heroku 这样的东西
  2. 想办法在互联网上给你的笔记本电脑起个名字。像https://portmap.io/

当你解决了这些问题后,我们回到这个问题的编程部分。默认情况下,httpskit 将使用任何主机名回答请求。所以你不需要做任何事情并且可以接受默认值。

'*' URL 与 URI 之间存在区别,我在掩饰它们


推荐阅读