vonH

vonH

I want to try my hand at my first Elixir website.
Basically I want to use the functions in an Elixir website to extend a compiled Pascal application. I plan to embed a language like Lua, Python or Lisp in the app later on, but when it comes to using a web app in some kind of psuedo REST application Elixir will do fine.

For instance if I want to write an arbitrary function such as sum(a+b) I want to call the Elixir website with the URL http://localhost:8000/sum?a=4&b=5 and the website would return 9 in plain text.

Would a plain simple Elixir script running a webserver accomplish that I should I start with something like Phoenix? I wouldn’t mind something very basic which doesn’t involve a framework, but if the framework would be just as helpful in learning Elixir’s basics I wouldn’t mind.

With regards to Phoenix I think the docs are a good start, but outside Phoenix what libraries or routines should I get started with.

Thanks!

First 10 of 31 Posts Switch mode

OvermindDL1

OvermindDL1

Basically about every webserver in Elixir is built on Erlang’s Cowboy, the most common one is Plug, which gives a simplified interface on Cowboy, where Plug just gives you a set of simple composable functions to build a pipeline. Phoenix is just mainly more functions built on Plug to make things even easier, like templating, as well as it has added two major things, one being a dead-simple and fast Websocket support, and the other being a fantastic and simple PubSub, all of which is optional and composable like any normal Plug. You can strip down Phoenix as much as you want but even when well loaded down it remains blazing fast.

If you are just wanting to call a url like you’ve shown and you want it to return just the text answer, no html or anything, raw Plug is fine, but if you ever intend to ever do something more than that, html, websockets, anything, you should just start with Phoenix now especially as its generators help encourage good and proper coding conventions for Elixir.

vonH

vonH OP

Do you know of any small online projects that would help me in the non-Phoenix path?

OvermindDL1

OvermindDL1

I don’t know of any projects off the top of my head (though I know I’ve seen a few), but the Plug Docs themselves contain examples, like the Plug.Router is about the most simple router you’d have, like you could hook up a sum path there, or build one dynamically by writing your own router as a plug or whatever. :slight_smile:

A forewarning, you will end up re-writing a lot of Phoenix stuff since Phoenix is just a fleshing out on Plug (made by the same devs as well), but if you are doing this to learn the back-end stuff, not a bad way to go. :slight_smile:

jeramyRR

jeramyRR

Not to be a debby downer here, but Phoenix is so fast to setup that you’ve probably spent more time writing the question than it would take to get an endpoint up and running in Phoenix. It’s amazing how quickly you can get something up. It isn’t very resource intensive either so the argument really comes down to, “What do you want to implement yourself?”

OvermindDL1

OvermindDL1

Exactly this.

xlphs

xlphs

If you are trying to cut down the number of dependencies, then cowboy and plug will do, here is my tic tac toe game for starters. And if you are interested, you can easily write a simple http server with help of :erlang.decode_packet/3 which parses HTTP headers for you.

vonH

vonH OP

I have made some progress so far, based on the Plug documentation and this stackoverflow question - http://stackoverflow.com/questions/25370007/how-to-pass-multiple-parameters-in-a-url-to-plug

defmodule MyRouter do
  import Plug.Conn
  use Plug.Router
  # import TemplateFunctions

  @alpha "alpha"
  @beta "beta"

  plug :match
  plug :dispatch


  def theta(a, b) do
    a + b
  end

  get "/hello" do
    send_resp(conn, 200, "world")
  end

  get "/hello/:name" do
    send_resp(conn, 200, "hello #{name}")
  end

  get "/sum" do
    conn = fetch_query_params(conn)
    %{ @alpha => alpha, @beta => beta } = conn.params
    # send_resp(conn, 200, " sum of #{alpha} and #{beta} is " ++ sum(alpha,beta))
    gamma = theta(alpha, beta)
    send_resp(conn, 200, " sum of #{alpha} and #{beta}")

  end
  get "/hello/*glob" do
    send_resp(conn, 200, "route after /hello: #{inspect glob}")
  end

  match _ do
    send_resp(conn, 404, "oops")
  end

  def theta2(a, b) do
    a + b
  end
end

When I run it intending to utilize the sum function, which I renamed theta because I thought it conflicted with some function in the libraries I get the error

   ** (exit) an exception was raised:                                                                  
        ** (ArithmeticError) bad argument in arithmetic expression                                      
            myfuncs/funcs_router.ex:14: MyRouter.theta/2                                                
            myfuncs/funcs_router.ex:29: anonymous fn/1 in MyRouter.do_match/4                           

with the full output below. There are other bugs here but what is the main reason for the failure to recognize the function ?

vonH@ac02:~/DevProjects/learnphoenix/tsys_functions$ iex -S mix                                  
Erlang/OTP 19 [erts-8.3] [source-d5c06c6] [64-bit] [smp:2:2] [async-threads:10] [hipe] [kernel-poll:
false]                                                                                              
                                                                                                    
Interactive Elixir (1.4.1) - press Ctrl+C to exit (type h() ENTER for help)                         
iex(1)>  c "myfuncs/funcs_router.ex"                                                                
warning: variable "gamma" is unused                                                                 
  myfuncs/funcs_router.ex:29                                                                        
                                                                                                    
[MyRouter]                                                                                          
iex(2)> {:ok, _} = Plug.Adapters.Cowboy.http MyRouter, []                                           
{:ok, #PID<0.185.0>}                                                                                
iex(3)>                                                                                             
20:03:53.003 [error] #PID<0.289.0> running MyRouter terminated                                      
Server: localhost:2001 (http)                                                                       
Request: GET /sum?alpha=4&beta=6                                                                    
** (exit) an exception was raised:                                                                  
    ** (ArithmeticError) bad argument in arithmetic expression                                      
        myfuncs/funcs_router.ex:14: MyRouter.theta/2                                                
        myfuncs/funcs_router.ex:29: anonymous fn/1 in MyRouter.do_match/4                           
        myfuncs/funcs_router.ex:1: MyRouter.plug_builder_call/2                                     
        (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4       
        (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

There are a few more questions.

  1. What code do I need to display all the parameters whether they match sum or not, eg ?alpha=6&beta=7&rho=8?pi=9 etc.

  2. When I add a parameter in addition alpha and beta the sum block works fine. If I want to match exactly 2 parameters how would I right the `get “/sum” matching code.

OvermindDL1

OvermindDL1

Well you are passing in strings to the theta function, then trying to add them, hence the (ArithmeticError) bad argument in arithmetic expression, so you should convert the param strings into integers first. :slight_smile:

String.to_integer/1 I think is what it is if you want a quick-fail one, otherwise Integer.parse/1 that tells you if successful or not.

OvermindDL1

OvermindDL1

That would just be conn.params.

Are you wanting to fail if they pass in extra arguments as well?

vonH

vonH OP

What function can format the whole of the conn.params variable for send_resp?

No in the case of a function like sum which could be adding many numbers tthat wouldn’t be necessary, it would simply be enough to check that all the parameters were numeric.

But in the case of wanting a fixed number of parameters what would be the best way, or fixed with a set of names? I have found an example in this article - http://nicolas-bettenburg.com/articles/scrubbing-get-params-with-phoenix/ - but I am not quite sure how dependent it is on Phoenix.

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement