简体   繁体   中英

Convert []byte slice to []int slice

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM