Http Client in Elm

Here’s the translation of the Go HTTP client example to Elm, formatted in Markdown for Hugo:

import Http
import Html exposing (Html, text)
import Task exposing (Task)

type Msg
    = GotResponse (Result Http.Error String)

main : Program () Model Msg
main =
    Browser.element
        { init = init
        , update = update
        , subscriptions = \_ -> Sub.none
        , view = view
        }

type alias Model =
    { responseStatus : String
    , responseBody : String
    }

init : () -> (Model, Cmd Msg)
init _ =
    ( { responseStatus = "", responseBody = "" }
    , Http.get
        { url = "https://elm-lang.org"
        , expect = Http.expectString GotResponse
        }
    )

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
        GotResponse result ->
            case result of
                Ok fullText ->
                    let
                        status = "200 OK"  -- Simplified, as Elm doesn't expose raw HTTP status
                        bodyLines = String.lines fullText |> List.take 5 |> String.join "\n"
                    in
                    ( { model | responseStatus = status, responseBody = bodyLines }
                    , Cmd.none
                    )
                
                Err _ ->
                    ( { model | responseStatus = "Error", responseBody = "Failed to fetch" }
                    , Cmd.none
                    )

view : Model -> Html Msg
view model =
    Html.div []
        [ Html.p [] [ text ("Response status: " ++ model.responseStatus) ]
        , Html.pre [] [ text model.responseBody ]
        ]

In Elm, HTTP requests are handled differently compared to imperative languages. Here’s an explanation of the Elm implementation:

  1. We use the Http module to make HTTP requests.
  2. The init function initiates the HTTP GET request when the application starts.
  3. We define a Msg type to handle the response from the HTTP request.
  4. The update function processes the response, extracting the status (simplified in this case) and the first 5 lines of the body.
  5. The view function renders the response status and body.

To run this Elm program:

  1. Save the code in a file, e.g., HttpClient.elm.
  2. Compile the Elm code to JavaScript:
$ elm make HttpClient.elm --output=httpclient.js
  1. Create an HTML file to load the compiled JavaScript:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Elm HTTP Client</title>
</head>
<body>
    <div id="elm"></div>
    <script src="httpclient.js"></script>
    <script>
        var app = Elm.HttpClient.init({
            node: document.getElementById('elm')
        });
    </script>
</body>
</html>
  1. Open the HTML file in a web browser to see the result.

This Elm implementation demonstrates how to make an HTTP GET request and handle the response in a functional, statically-typed language designed for building web applications.