dongshang6062 2016-09-11 13:41
浏览 259
已采纳

在Golang中,无法从int64转换为字符串,然后进行切片

I've have this code on a client that receives a gzipped response from an API :

client := &http.Client{}
response, _ := client.Do(r)

// Check that the server actual sent compressed data
var reader io.ReadCloser
switch response.Header.Get("Content-Encoding") {
case "gzip":
    reader, err := gzip.NewReader(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    defer reader.Close()
default:
    reader = response.Body
}

token, err := io.Copy(os.Stdout, reader)
if err != nil {
    log.Fatal(err)
}

cadenita := strconv.FormatInt(token, 10)

fmt.Println(cadenita)

cadena := "code=b2cc1793-cb7a-ea8d-3c82-766557"
fmt.Println(cadena[5:])

This code shows : enter image description here

But, if I use [5:] directly on cadenita, although it's also a string, I have this error.

enter image description here

I want to be able to slice and regex on the token(int64) transformed in a string. How can I do so ?

  • 写回答

1条回答 默认 最新

  • dty97501 2016-09-11 15:10
    关注

    io.Copy returns the number of bytes copied, so that's the value thats in your token variable, so somewhere in the area of 40 for your example. FormatInt converts that to a string "40" which only has 2 chars, so it'll error as you see when you ask for the substring starting at char 5 of "40".

    Are you trying to get the actual response data in token? if so you'll need to copy it into a buffer, e.g.

    buff := bytes.Buffer{}
    _, err := io.Copy(&buff, reader)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(buff.String()[5:])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容