在Golang中,从int64转换为字符串,然后再转换为切片的方法不起作用。

huangapple go评论73阅读模式
英文:

In Golang, transformation from int64 to string and then slice doesn't work

问题

我有一个客户端代码,从API接收到一个经过gzip压缩的响应:

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

// 检查服务器是否实际发送了压缩数据
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:])

这段代码显示了以下内容:

在Golang中,从int64转换为字符串,然后再转换为切片的方法不起作用。

但是,如果我直接在cadenita上使用[5:]进行切片,尽管它也是一个字符串,我会遇到这个错误。

在Golang中,从int64转换为字符串,然后再转换为切片的方法不起作用。

我想要能够在转换为字符串的token(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 :
在Golang中,从int64转换为字符串,然后再转换为切片的方法不起作用。

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

在Golang中,从int64转换为字符串,然后再转换为切片的方法不起作用。

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

答案1

得分: 2

io.Copy返回复制的字节数,所以这就是你的token变量中的值,所以在你的示例中大约是40。FormatInt将其转换为字符串"40",该字符串只有2个字符,所以当你请求从"40"的第5个字符开始的子字符串时,会出现错误。

你是想获取token中的实际响应数据吗?如果是的话,你需要将其复制到一个缓冲区中,例如:

buff := bytes.Buffer{}
_, err := io.Copy(&buff, reader)
if err != nil {
    log.Fatal(err)
}
fmt.Println(buff.String()[5:])
英文:

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:])

huangapple
  • 本文由 发表于 2016年9月11日 21:41:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/39436701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定