-2

我正在尝试使用给定 ID 22024283 访问 HackerNews API 端点,它代表特定的新闻项目,例如https://hacker-news.firebaseio.com/v0/22024283.json

此 itemID 是类型uint8,我需要将其转换为它的string表示形式以插入 URL。

我不能使用strconv.Itoa(int(id)),因为它会产生数字 91 而不会保留 22024283。

对此的任何帮助将不胜感激。到目前为止,这是我的代码,感兴趣的功能是GetHackerNewsItem()


import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
    "time"
)

//Client represents connection to firebase datastore
type Client struct {
    BASEURI string
    Version string
    Suffix  string
}
type Item struct {
    id          int       `json:"id"`
    itemtype    string    `json:"itemtype"`
    by          string    `json:"by"`
    time        time.Time `json:"time"`
    kids        []int     `json:"kids"`
    url         string    `json:"url"`
    score       int       `json:"score"`
    text        string    `json:"text"`
    title       string    `json:"title"`
    descendants int       `json:"descendants"`
}

//Connect to firebase datastore
func NewHackerNewsClient() *Client {
    var client Client
    client.BASEURI = "https://hacker-news.firebaseio.com/"
    client.Version = "v0"
    client.Suffix = ".json"
    return &client
}
func MakeHTTPRequest(url string) ([]byte, error) {
    response, err := http.Get(url)
    if err != nil {
        fmt.Printf("The http request failed with the error %s\n", err)
    }
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Printf("Failed to read response data with the error %s\n", err)
        return nil, err
    }
    return body, nil

}

func (client *Client) GetHackerNewsItem(id uint8) []byte {
    itemID := strconv.Itoa(int(id))
    fmt.Printf(itemID)
    url := client.BASEURI + client.Version + itemID + client.Suffix
    fmt.Printf(url)
    item, _ := MakeHTTPRequest(url)
    fmt.Print(item)
    return item
}
func (client *Client) GetTopStories() {

    url := client.BASEURI + client.Version + "/topstories/" + client.Suffix
    itemArray, _ := MakeHTTPRequest(url)
    for i := 0; i < len(itemArray); i++ {
        item := client.GetHackerNewsItem(itemArray[i])
        fmt.Print(item)
    }
}

func main() {
    client := NewHackerNewsClient()
    client.GetTopStories()

}
4

1 回答 1

1

itemArray, _ := MakeHTTPRequest(url)

itemArray必须像

dat := make([]uint64, 0)
if err := json.Unmarshal(itemArray, &dat); err != nil {
        panic(err)
}
于 2020-01-15T13:11:57.160 回答