我正在尝试使用给定的ID访问HackerNews API端点,该ID 22024283代表特定的新闻项,例如 https://hacker-news.firebaseio.com/v0/22024283.json
此 itemID 的类型为uint8
,我需要将其转换为要插入到 URL 中的string
表示形式。
我不能使用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 %sn", err)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("Failed to read response data with the error %sn", 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()
}
itemArray, _ := MakeHTTPRequest(url(
itemArray必须像
dat := make([]uint64, 0)
if err := json.Unmarshal(itemArray, &dat); err != nil {
panic(err)
}