Search code examples
httpjuliaresponsehttp-status-codes

How to collect HTTP response status using Genie.jl in Julia


How to collect the HTTP response status for a script? Below is a sample code which will start a server and allow two routes for interaction.

using Genie
import Genie.Router: route
import Genie.Renderer.Json: json

Genie.config.run_as_server = true

route("/try/", method=GET) do
  (:message => "Welcome") |> json
end

route("/test/", method=POST) do
  data = jsonpayload()
  <body>
end
Genie.startup()

How to collect the response status like 200, 500 or others as a string variable?


Solution

  • Open connection to your server using HTTP and look for the status field:

    julia> using HTTP
    
    julia> response = HTTP.get("http://127.0.0.1:8000/try")
    HTTP.Messages.Response:
    """
    HTTP/1.1 200 OK
    Content-Type: application/json; charset=utf-8
    Server: Genie/1.18.1/Julia/1.6.1
    Transfer-Encoding: chunked
    
    {"message":"Welcome"}"""
    
    julia> response.status
    200
    

    If you rather want to control the status yourself you can add on the server side:

     route("/tryerror/", method=GET) do
         Genie.Responses.setstatus(503)
     end
    

    And now let us test it for 503:

    julia> response = HTTP.get("http://127.0.0.1:8000/tryerror")
    ERROR: HTTP.ExceptionRequest.StatusError(503, "GET", "/tryerror", HTTP.Messages.Response:
    """
    HTTP/1.1 503 Service Unavailable
    Content-Type:
    Server: Genie/1.18.1/Julia/1.6.1
    Transfer-Encoding: chunked
    
    """)