douyinghuo8874
douyinghuo8874
2019-05-08 01:51

访问链接后获取输出字符串

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

I am writing a program by Go. In this program, I access to a website and in this website, it will print a string. I want to get this string for next process. For example:

I access by curl and the returned string will like that:

curl localhost:4000
abc_example

I need to get "abc_example" for next process in my program. Now, this problem was solved.

Actually, my result will be a JSON like that:

{"name":"xyz_example"}

How can I parse this string and just get "xyz_example"

I am a newbie in Go. May you help me. Thank you!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doubing3662 doubing3662 2年前

    Here's an example of reading the response from an HTTP request. I would recommend reading up on the documentation for the http package, and maybe a simple tutorial like 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)
    }
    
    点赞 评论 复制链接分享