卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35316本站已运行395

如何像使用 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 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
            }
        }
    }
}
卓越飞翔博客
上一篇: 动态 SQL 集 Golang
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏