登录
首页 >  Golang >  Go问答

使用 net/http 设置 GET 请求的读取回调,与 go-curl 实现相同效果的方法是什么?

来源:stackoverflow

时间:2024-02-06 19:59:19 320浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《使用 net/http 设置 GET 请求的读取回调,与 go-curl 实现相同效果的方法是什么?》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我们有一个有效的 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
            }
        }
    }
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>