add: multihost pedestal e.g

This commit is contained in:
matheusfrancisco 2024-02-04 14:09:06 -03:00
parent 989ab72a58
commit 8be0b8c322
No known key found for this signature in database
GPG key ID: 9800E78095056503
3 changed files with 92 additions and 0 deletions

13
examples/pedestal-multi-host/.gitignore vendored Normal file
View file

@ -0,0 +1,13 @@
/target
/classes
/checkouts
pom.xml
pom.xml.asc
*.jar
*.class
/.lein-*
/.nrepl-port
.hgignore
.hg/
.lsp/
.clj-kondo/

View file

@ -0,0 +1,8 @@
(defproject pedestal-multi-host "0.1.0-SNAPSHOT"
:description "Reitit-http with pedestal multi host example"
:dependencies [[org.clojure/clojure "1.10.0"]
[io.pedestal/pedestal.service "0.5.5"]
[io.pedestal/pedestal.jetty "0.5.5"]
[metosin/reitit-pedestal "0.7.0-alpha7"]
[metosin/reitit "0.7.0-alpha7"]]
:repl-options {:init-ns example.server})

View file

@ -0,0 +1,71 @@
(ns example.server
(:require [io.pedestal.http :as server]
[clojure.core.async :as a]
[reitit.pedestal :as pedestal]
[muuntaja.interceptor]
[reitit.http :as http]
[reitit.ring :as ring]))
(defn interceptor [x]
{:enter (fn [ctx] (update-in ctx [:request :via] (fnil conj []) {:enter x}))
:leave (fn [ctx] (update-in ctx [:response :body] conj {:leave x}))})
(defn handler [{:keys [via]}]
{:status 200,
:body (conj via :handler)})
(def async-handler
{:enter (fn [{:keys [request] :as ctx}]
(a/go (assoc ctx :response (handler request))))})
(def router
(pedestal/routing-interceptor
(http/router
[""
["/api/v2"
{:host "example.com"}
["/sync"
{:get {:handler (fn [req]
{:status 200
:body {:v2 "example.com"}})}}]]
["/api"
{:host "localhost"
:interceptors [(interceptor :api)]}
["/sync"
{:interceptors [(interceptor :sync)]
:get {:interceptors [(interceptor :get)]
:handler handler}}]
["/async"
{:interceptors [(interceptor :async)]
:get {:interceptors [(interceptor :get) async-handler]}}]]]
;; optional interceptors for all matched routes
{:data {:interceptors [(interceptor :router)]}})
;; optional default ring handlers (if no routes have matched)
(ring/routes
(ring/create-resource-handler)
(ring/create-default-handler))
;; optional top-level routes for both routes & default route
{:interceptors [(muuntaja.interceptor/format-interceptor)
(interceptor :top)]}))
(defn start []
(-> {::server/type :jetty
::server/port 3000
::server/join? false
;; no pedestal routes
::server/routes []}
(server/default-interceptors)
;; use the reitit router
(pedestal/replace-last-interceptor router)
(server/dev-interceptors)
(server/create-server)
(server/start))
(println "server running in port 3000"))
(comment
(start))