Skip to content

Instantly share code, notes, and snippets.

@ruxo
Last active February 9, 2023 23:18
Show Gist options
  • Select an option

  • Save ruxo/f003180a94b79b8e32ea to your computer and use it in GitHub Desktop.

Select an option

Save ruxo/f003180a94b79b8e32ea to your computer and use it in GitHub Desktop.
HTTP !!!
#r "System.Net.Http.dll"
#r "packages/Newtonsoft.Json/lib/net45/Newtonsoft.Json.dll"
#load "paket-files/ruxo/a9244a6dfe5e73337261/common.fs"
#load "paket-files/ruxo/5e1e84865bafd17e3a34/pair.fs"
open System
open System.Net
open RZ
open RZ.Foundation
type Uri with
member x.Combine(path:string) = Uri(x, path)
type UserName = string
type Password = string
type AccountAuthentication = UserName * Password
module Http =
open System.Net.Http
type HttpResult<'a> = HttpStatusCode * 'a
type HttpClientFactory = unit -> HttpClient
let private defaultFactory() = new HttpClient()
let private getAsync (uri: Uri) (client: HttpClient) = client.GetAsync(uri) |> Async.AwaitTask
let private putAsync data (uri: Uri) (client: HttpClient) = client.PutAsync(uri, data) |> Async.AwaitTask
let private readAsString(content: HttpContent) = content.ReadAsStringAsync() |> Async.AwaitTask
let private readAsByteArray(content: HttpContent) = content.ReadAsByteArrayAsync() |> Async.AwaitTask
let private simpleRequest requester reader clientFactory uri =
async {
use (client: HttpClient) = clientFactory()
let! (response: HttpResponseMessage) = requester uri client
let! body = response.Content |> reader
return response.StatusCode, body
}
let getContent = simpleRequest getAsync readAsByteArray
let get = simpleRequest getAsync readAsString
let put data = simpleRequest (putAsync <| new ByteArrayContent(data)) readAsString
module HttpClientFactory =
open System.Net.Http
let createBasicAuthenHeader(user, pass) =
let param =
sprintf "%s:%s" user pass
|> Text.Encoding.ASCII.GetBytes
|> Convert.ToBase64String
Headers.AuthenticationHeaderValue("Basic", param)
let withSimpleAuthen acc =
fun() ->
let client = new HttpClient()
client.DefaultRequestHeaders.Authorization <- createBasicAuthenHeader acc
client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment