dt614037527
dt614037527
2019-07-04 04:51

如何解决多个分配中的分配[] byte数据

How to fix this problem about datatype of this function.

Firstly, I'm new to Golang and am trying to learn it with some practice. I created a function to handle a request/GET http response.

func connect(url, token string) (data byte) {
    var bearer = "Bearer " + token
    res, err := http.Get(url)
    res.Header.Add("Authorization", bearer)
    defer res.Body.Close()
    data, _ := ioutil.ReadAll(res.Body)

    return data
}

The error warning.

cannot assign []byte to data (type byte) in multiple assignment

I just want the function to return raw data from API response

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doufang3001 doufang3001 2年前

    The return type of your function is of type byte, whereas the return type of ioutil.ReadAll is []byte. Those types do not match, where one is a byte and the other is a slice of bytes. Change the return type of data to []byte, assuming that is what you wanted in the first place.

    func connect(url, token string) (data []byte) {
        var bearer = "Bearer " + token
        res, err := http.Get(url)
        res.Header.Add("Authorization", bearer)
        defer res.Body.Close()
        data, _ := ioutil.ReadAll(res.Body)
    
        return data
    }
    
    点赞 评论 复制链接分享