登录
首页 >  Golang >  Go问答

在打开链接后接收字符串输出

来源:stackoverflow

时间:2024-03-24 10:57:47 263浏览 收藏

在 Go 语言中,可以通过发送 HTTP 请求并读取响应来获取网站打印的字符串。通过使用 `ioutil.ReadAll` 函数,可以将响应主体中的字节读取到一个字符串中。对于 JSON 响应,可以使用 JSON 解码器包将其解析为 Go 结构体,从而访问其中的值。

问题内容

我正在用 go 编写一个程序。 在这个程序中,我访问一个网站,在这个网站中,它将打印一个字符串。我想获取这个字符串用于下一个过程。 例如:

我通过curl访问,返回的字符串将是这样的:

curl localhost:4000
abc_example

我需要为程序中的下一个进程获取“abc_example”。 现在,这个问题已经解决了。

实际上,我的结果将是这样的 json:

{"name":"xyz_example"}

如何解析这个字符串并得到“xyz_example”

我是 go 的新手。愿你帮助我。 谢谢!


解决方案


以下是从 http 请求读取响应的示例。 我建议阅读 documentation 的 http 包,也许还有像 this one 这样的简单教程。

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {
    //make a request
    response, err := http.Get("https://mdtf.org")
    if err != nil {
      fmt.Println("error making request: ", err)
      return
    }

    //make sure the response body gets closed
    defer response.Body.Close()

    //read the bytes
    responseBytes, err := ioutil.ReadAll(response.Body)
    if err != nil {
      fmt.Println("error reading response bytes: ", err)
      return
    }

    //turn the response bytes into a string
    responseString := string(responseBytes)

    //print it or something
    fmt.Println(responseString)
}

今天关于《在打开链接后接收字符串输出》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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