如何像使用 go-curl 一样为 net/http GET 请求设置读取回调?

如何像使用 go-curl 一样为 net/http get 请求设置读取回调?

php小编西瓜为您介绍如何为net/http GET请求设置读取回调,实现类似于go-curl的功能。在使用net/http库发起GET请求时,我们可以利用http.Client和http.Request结构体的相关方法来设置读取回调函数。通过设置http.Response.Body的值为一个实现了io.Reader接口的自定义结构体,我们可以在读取响应内容的同时执行回调操作。这样,我们就能够在处理HTTP请求的过程中实现更加灵活和自定义的操作,提升代码的可维护性和扩展性。

问题内容

我们有一个有效的 golang 程序,可以从大华相机获取快照/图像。我们希望对此进行增强,为以下 URI 添加读取回调函数 – http://192.168.x.x/cgi-bin/eventManager.cgi?action=attach&codes=[VideoMotion]。此 URI 使套接字从相机端保持打开状态,相机通过它不断发送事件。

我们尝试使用 go-curl,因为它支持注册读取回调。但是,该软件包不支持 MIPS 架构。因此,我们无法使用它。任何建议/帮助都是有益的。这是快照获取的工作代码。

package mainimport (    "fmt"    "log"    "net/http"    "github.com/icholy/digest")const (    username = "xxxxx"    password = "xxxxx"    uri = "http://192.168.x.x/cgi-bin/snapshot.cgi")func main() {    client := &http.Client{        Transport: &digest.Transport{            Username: username,            Password: password,        },    }    resp, err := client.Get(uri)    if err != nil {        log.Fatal(err)    }    defer resp.Body.Close()    if resp.StatusCode != http.StatusOK {        log.Fatalf("Error: Status code %d", resp.StatusCode)    } else {        fmt.Println("Snapshot fetched")    }    // Perform next steps}

登录后复制

解决方法

这是我的误解,认为 client.Get(uri) 调用被阻止。 @kotix 的以下评论让我重新思考代码。在client.Get(uri)下面添加打印后,确认继续执行。

这是在事件到达时打印事件的完整代码。

package mainimport (    "log"    "net/http"    "io"    "github.com/icholy/digest")const (    username = "xxxx"    password = "xxxx"    uri = "http://192.168.x.xxx/cgi-bin/eventManager.cgi?action=attach&codes=[VideoMotion]")func main() {    client := &http.Client{        Transport: &digest.Transport{            Username: username,            Password: password,        },    }    resp, err := client.Get(uri)    if err != nil {        log.Fatal(err)    }    defer resp.Body.Close()    log.Print("Coming here");    if resp.StatusCode != http.StatusOK {        log.Fatalf("Error: Status code %d", resp.StatusCode)    } else {        buffer := make([]byte, 4096) // Adjust the buffer size as needed        for {            n, err := resp.Body.Read(buffer)            if err != nil && err != io.EOF {                log.Fatal(err)            }            if n > 0 {                // Process the chunk of data                bodyString := string(buffer[:n])                log.Print(bodyString)            }            if err == io.EOF {                break            }        }    }}

登录后复制

以上就是如何像使用 go-curl 一样为 net/http GET 请求设置读取回调?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2483873.html

(0)
上一篇 2025年3月4日 21:24:56
下一篇 2025年2月22日 20:23:56

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论