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!

Showing Posts 1 to 10

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

itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New
rlipscombe
When I use Mix.install with a git dependency, using git@github.com:... how do I change the SSH identity used? I’ve got two Github accoun...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews