Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Print Request as curl #119

Open
haf opened this issue Feb 19, 2017 · 0 comments
Open

Print Request as curl #119

haf opened this issue Feb 19, 2017 · 0 comments

Comments

@haf
Copy link
Owner

haf commented Feb 19, 2017

A nice way for doing sanity checking and also for checking what the formatted output of for example the request uri is. Like this, in the Request module, but fully featured and property-tested:

    let asCurl (req : Request) : string =
      let cmd _ = Some [ "curl" ]

      let printHeaders _ =
        Some [ "-i" ]

      let method req =
        if req.method <> Get then ["-X"; req.method.ToString()] |> Some
        else None

      let uri (req : Request) =
        let ub = UriBuilder req.url
        ub.Query <- Impl.getQueryString Encoding.UTF8 req
        Some [ ub.Uri.ToString() ]
      
      let form (req : Request) =
        match req.body with
        | BodyForm form ->
          form
          |> List.choose (function
            | NameValue (name, value) ->
              Some (name, value)
            | _ ->
              None)
          |> List.map (fun (name, value) ->
            [ "-d"; sprintf "\"%s=%s\"" name value ]
          )
          |> List.concat
          |> Some
        | _ ->
          None

      let basic (req: Request) =
        match req.headers |> Map.tryFind "Authorization" with
        | None -> None
        | Some (Authorization value) when value.StartsWith("Basic") ->
          match value.Split(' ') with
          | [| kind; base64Value |] -> // horrible hack; not calculating the base64 encoding until last responsible moment is the right fix
            let converted = UTF8.toString (Convert.FromBase64String base64Value)
            Some [ "-u"; sprintf "\"%s\"" converted ]
          | _ ->
            None
        | _ ->
          None

      [ cmd
        printHeaders
        method
        uri
        form
        basic
      ]
      |> List.map (fun f -> f req)
      |> List.filter Option.isSome
      |> List.map Option.get
      |> List.concat
      |> String.concat " "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant