代码之家  ›  专栏  ›  技术社区  ›  ca9163d9

在最后一个链接的option.bind中得到中间值了吗?

f#
  •  0
  • ca9163d9  · 技术社区  · 7 年前

    let getHtml location = 
        let request (url:string) = 
            let response = httpRequest (getFullUri url)
            response.Headers.TryFind "Location"
    
        request location  
        |> Option.bind (fun x -> request x) 
        |> Option.bind (fun x -> request x) // need the return of httpRequest inside request
    

    我要代码返回的最后一个调用 httpRequest . 不是归还 request


    更新:尝试了以下代码。最后一个错误 snd . 我想我可以使用可变变量来实现它。但这是习惯用法吗?

    let getHtml location = 
        let request (url:string) = 
            let response = httpRequest (getFullUri url)
            match response.Headers.TryFind "Location" with 
            | Some location -> Some location, response
            | None -> None, response
    
        request location |> fst
        |> Option.bind (fun x -> request x |> fst) 
        |> Option.bind (fun x -> request x |> snd) // Error on snd
    

    使用可变变量?

    let getHtml location = 
        let mutable resp : FSharp.Data.HttpResponse = ???
        let request (url:string) = 
            let response = httpRequest (getFullUri url)
            resp <- response
            response.Headers.TryFind "Location"
    
        request location 
        |> Option.bind (fun x -> request x) 
        |> Option.bind (fun x -> request x)
    
        if not (resp = null) then Some resp else None
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Aaron M. Eshbach    7 年前

    我想你想做的其实是 getHtml 递归,这样当HTTP请求返回201或300级响应代码时,您可以按照 Location 标题指向重定向页面并返回正确的HTML。你可以用一个简单的模式匹配 response.StatusCode 以及位置标题,如下所示:

    open FSharp.Data
    
    // stub
    let getFullUri (url: string) = 
        sprintf "%A" <| System.UriBuilder(url)
    
    // stub
    let httpRequest = Http.Request
    
    // fetches the requested URL, following redirects as necessary
    let rec getHtml location = 
        let response = httpRequest (getFullUri location)
        match response.StatusCode, response.Headers |> Map.tryFind "Location" with
        | (status, Some redirectUrl) when status = 201 || (status >= 300 && status < 400) -> 
            getHtml redirectUrl
        | _ -> 
            response
    

    这就是你想要的吗?我用以下返回302的url测试了它,得到了它被重定向到的页面的html: https://jigsaw.w3.org/HTTP/300/302.html