将 []byte 切片转换为 []int 切片。

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

Convert []byte slice to []int slice

问题

以下代码的功能是什么:

它访问给定的URL,并返回一个由随机数字组成的纯文本。此时,数据是一个切片 []byte,但我想使用这些数据,所以我认为最好的解决方案是将数据转换为切片 []int。

以下是我的代码:

func getRandomInt(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    resp, err := http.Get("https://www.random.org/integers/?num=5&min=1&max=10&col=1&base=10&format=plain&rnd=new")
    if err != nil {
        fmt.Println("No response from request")
    }

    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body) // response body is []byte

    if err != nil {
        fmt.Println(err)
    }

    err = json.Unmarshal(body, &bodyInt)

    if err != nil {
        fmt.Println(err)
    }

    //我的转换器
    bodyInt := make([]int, len(body))
    for i, b := range body {
        bodyInt[i] = int(b)
    }

    js, err := json.Marshal(bodyInt)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Write(js)
    fmt.Println("Endpoint Hit: getRandomInt")
}

我尝试了一些转换。根据给定的URL,我应该得到1到10范围内的5个数字。但是,转换后我得到的是10到60范围内的10-11个数字。

我进行了一些测试,当body的结构如下所示时,转换工作正常。

body = []byte{1, 2, 3, 4, 5}

所以我认为我以稍微不同的格式从URL响应中读取了数据,但不知道如何解决这个问题。谢谢。

英文:

What the code below does:

It gets to a given URL and responses with a plain text made of random numbers. At this moment the data is slice []byte, but I'd like to use those data so I think best solution would be to convert data to slice []int.

Here comes my code:

func getRandomInt(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

	resp, err := http.Get("https://www.random.org/integers/?num=5&min=1&max=10&col=1&base=10&format=plain&rnd=new")
    if err != nil {
    	fmt.Println("No response from request")
    }

    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body) // response body is []byte

    if err != nil {
    	fmt.Println(err)
    }

    err = json.Unmarshal(body, &bodyInt)

    if err != nil {
    	fmt.Println(err)
    }

    //MY CONVERTER
    bodyInt := make([]int, len(body))
    for i, b := range body {
    	bodyInt[i] = int(b)
    }

    js, err := json.Marshal(bodyInt)
    if err != nil {
    	http.Error(w, err.Error(), http.StatusInternalServerError)
    	return
    }

    w.Write(js)
    fmt.Println("Endpoint Hit: getRandomInt")
}

I've tried to do a little bit of conversion myself. With given URL I should get 5 numbers in the range of 1 to 10. What I get after conversion are 10-11 numbers in the range of 10 to 60.

I did some tests and when the structure of body is like below, cnversion works fine.

body = []byte{1, 2, 3, 4, 5}

So I think I read data from url response in a little different format, but have no idea how to solve that issue. Thanks.

答案1

得分: 2

如果你使用curl命令访问该URL,你会清楚地看到响应不是JSON格式的,所以你不应该将其视为JSON。

curl 'https://www.random.org/integers/?num=5&min=1&max=10&col=1&base=10&format=plain&rnd=new'
5
10
4
4
2

它只是一个以换行符分隔的整数列表,所以你应该将其视为这样处理。

resp, err := http.Get("https://www.random.org/integers/?num=5&min=1&max=10&col=1&base=10&format=plain&rnd=new")
if err != nil {
    fmt.Println(err)
    return
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
    fmt.Println(err)
    return
}

lines := strings.Split(string(body), "\n")
numbers := []int{}
for i := range lines {
    line := strings.TrimSpace(lines[i])
    if line == "" {
        continue
    }

    num, err := strconv.Atoi(line)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    numbers = append(numbers, num)
}

// 使用numbers做一些操作
英文:

If you curl that URL you can clearly see that the response is not JSON, so you shouldn't treat it as such.

curl 'https://www.random.org/integers/?num=5&min=1&max=10&col=1&base=10&format=plain&rnd=new'
5
10
4
4
2

It's just a new-line separated list of integers, so you should treat it as such.

resp, err := http.Get("https://www.random.org/integers/?num=5&min=1&max=10&col=1&base=10&format=plain&rnd=new")
if err != nil {
    fmt.Println(err)
    return
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
    fmt.Println(err)
    return
}

lines := strings.Split(string(body), "\n")
numbers := []int{}
for i := range lines {
    line := strings.TrimSpace(lines[i])
    if line == "" {
        continue
    }

    num, err := strconv.Atoi(line)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    numbers = append(numbers, num)
}

// do something with numbers

huangapple
  • 本文由 发表于 2021年12月16日 19:57:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/70378625.html
匿名

发表评论

匿名网友

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

确定