Http Client in F#
Here’s the translation of the Go HTTP client example to F#, formatted in Markdown suitable for Hugo:
Our example demonstrates how to create a simple HTTP client using F#. The F# standard library provides excellent support for HTTP clients through the System.Net.Http
namespace.
open System
open System.Net.Http
open System.IO
[<EntryPoint>]
let main argv =
// Create an instance of HttpClient
use client = new HttpClient()
// Issue an HTTP GET request to a server
let response =
client.GetAsync("https://gobyexample.com")
|> Async.AwaitTask
|> Async.RunSynchronously
// Ensure the request was successful
response.EnsureSuccessStatusCode() |> ignore
// Print the HTTP response status
printfn "Response status: %A" response.StatusCode
// Read the response content as a string
let content =
response.Content.ReadAsStringAsync()
|> Async.AwaitTask
|> Async.RunSynchronously
// Print the first 5 lines of the response body
let lines = content.Split('\n')
lines
|> Array.take (min 5 lines.Length)
|> Array.iter (printfn "%s")
0 // return an integer exit code
In this F# example:
We use
System.Net.Http.HttpClient
to send HTTP requests. This is similar to thehttp.Client
in the original example.We create an instance of
HttpClient
using ause
binding, which ensures the client is properly disposed of when it’s no longer needed.We send a GET request using
client.GetAsync()
. This is an asynchronous operation, so we use F#’s async workflows to handle it.We print the response status using
printfn
, which is similar tofmt.Println
in the original example.To read the response body, we use
ReadAsStringAsync()
and then split the content into lines.We print the first 5 lines of the response body using F#’s array functions.
To run this program, save it as HttpClient.fs
and use the F# compiler:
$ dotnet fsi HttpClient.fs
Response status: OK
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Go by Example</title>
This F# version provides equivalent functionality to the original example, demonstrating how to make HTTP requests and process responses in F#.