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

问题描述 投票:0回答:1

我们有一个有效的 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
}
go http callback
1个回答
0
投票

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

好的,那么从 resp.Body 读取数据并检查 resp 字段来代替 // 执行后续步骤注释有什么问题?

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

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
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.