Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. plug :match
  2. plug Plug.Static, at: "/pub", from: :cerber
  3. plug :dispatch
  4.  
  5. get "/" do
  6. Logger.info "GET /"
  7. send_resp(conn, 200, "Hello worldn")
  8. end
  9.  
  10. defmodule Server do
  11. use Plug.Builder
  12. plug Plug.Logger
  13. plug Plug.Static, at: "/", from: "/path/to/static"
  14. end
  15.  
  16. defmodule HttpServer.Application do
  17. require Logger
  18. use Application
  19.  
  20. def start(_type, _args) do
  21. children = [
  22. {Plug.Adapters.Cowboy2, scheme: :http, plug: HttpServer.Router, options: [port: 4002]}
  23. ]
  24.  
  25. opts = [strategy: :one_for_one, name: HttpServer.Supervisor]
  26.  
  27. Supervisor.start_link(children, opts)
  28. end
  29. end
  30.  
  31. defmodule HttpServer.Router do
  32. use Plug.Router
  33.  
  34. plug(Plug.Logger)
  35. plug(:redirect_index)
  36. plug(:match)
  37. plug(:dispatch)
  38.  
  39. forward("/static", to: HttpServer.StaticResources)
  40.  
  41. get "/sse" do
  42. # some other stuff...
  43. conn
  44. end
  45.  
  46. match _ do
  47. send_resp(conn, 404, "not found")
  48. end
  49.  
  50. def redirect_index(%Plug.Conn{path_info: path} = conn, _opts) do
  51. case path do
  52. [] ->
  53. %{conn | path_info: ["static", "index.html"]}
  54.  
  55. ["favicon.ico"] ->
  56. %{conn | path_info: ["static", "favicon.ico"]}
  57.  
  58. _ ->
  59. conn
  60. end
  61. end
  62. end
  63.  
  64. defmodule HttpServer.StaticResources do
  65. use Plug.Builder
  66.  
  67. plug(
  68. Plug.Static,
  69. at: "/",
  70. from: :http_server
  71. )
  72.  
  73. plug(:not_found)
  74.  
  75. def not_found(conn, _) do
  76. send_resp(conn, 404, "static resource not found")
  77. end
  78. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement