2017-01-06 88 views
1

我探索藥劑的世界,並建立以下內容:檢查URL參數是一個數字

defmodule Hello do 
    def init(default_opts) do 
    IO.puts "starting up App..." 
    default_opts 
    end 

def call(conn, _opts) do 
    route(conn.method, conn.path_info, conn) 
end 

def route("GET", ["customers", cust_id], conn) do 
    # check parameter 
    IO.puts user_id 
    IO.puts "Check if user_id is a number:" 
    IO.puts is_number(cust_id) 

    if is_number(cust_id) do 
    conn |> Plug.Conn.send_resp(200, "Customer id: #{cust_id}") 
    else 
    conn |> Plug.Conn.send_resp(404, "Couldn't find customer, sorry!") 
    end 

end 

我很奇怪,爲什麼is_number功能(或is_integer)是提供虛假的結果。我使用的網址是:http://localhost:4000/customers/12

回答

1

is_number(cust_id)是錯誤的,因爲cust_id是一個包含整數數字的字符串,但它實際上並不是一個數字。它可以將解析爲一個整數,但它是一個字符串,因爲conn.path_info不會自動將整數看起來的字符串轉換爲整數。您可以使用Integer.parse/2來檢查字符串是否是有效整數:

if match?({_, ""}, Integer.parse(cust_id)) do 
    conn |> Plug.Conn.send_resp(200, "Customer id: #{cust_id}") 
else 
    conn |> Plug.Conn.send_resp(404, "Couldn't find customer, sorry!") 
end 
相關問題