Access HTTP response as string in Go

后端 未结 3 1275
鱼传尺愫
鱼传尺愫 2020-12-12 13:16

I\'d like to parse the response of a web request, but I\'m getting trouble accessing it as string.

func main() {
    resp, err := http.Get(\"http://google.h         


        
相关标签:
3条回答
  • 2020-12-12 13:45

    string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.

    0 讨论(0)
  • 2020-12-12 13:50

    bs := string(body) should be enough to give you a string.

    From there, you can use it as a regular string.

    A bit as in this thread:

    var client http.Client
    resp, err := client.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    
    if resp.StatusCode == http.StatusOK {
        bodyBytes, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
        bodyString := string(bodyBytes)
        log.Info(bodyString)
    }
    

    See also GoByExample.

    As commented below (and in zzn's answer), this is a conversion (see spec).
    See "How expensive is []byte(string)?" (reverse problem, but the same conclusion apply) where zzzz mentioned:

    Some conversions are the same as a cast, like uint(myIntvar), which just reinterprets the bits in place.

    Sonia adds:

    Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
    Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. The bytes.Buffer type is often useful.

    0 讨论(0)
  • 2020-12-12 13:58

    The method you're using to read the http body response returns a byte slice:

    func ReadAll(r io.Reader) ([]byte, error)
    

    official documentation

    You can convert []byte to a string by using

    body, err := ioutil.ReadAll(resp.Body)
    bodyString := string(body)
    
    0 讨论(0)
提交回复
热议问题