首页 > 后端开发 > 戈兰 > 正文

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

WBOY
发布: 2024-02-11 09:24:08
转载
259 人浏览过

如何像使用 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 main

import (
    "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 main

import (
    "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 请求设置读取回调?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!