-2

I'm trying to access the HackerNews API endpoint with a given ID 22024283 which represents a particular news item e.g https://hacker-news.firebaseio.com/v0/22024283.json

This itemID is of type uint8and I need to convert this to it's string representation to insert into the URL.

I cannot use strconv.Itoa(int(id)) as that will produce the number 91 and not preserve 22024283.

Any help on this would be appreciated. Here is my code so far, function of interest is 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()

}
Zoe
  • 27,060
  • 21
  • 118
  • 148
mangokitty
  • 1,759
  • 3
  • 12
  • 17
  • 4
    `uint8` has a valid range of `0..255`, so the number `22024283` cannot possibly be of type `uint8`. Use another type, e.g. `int`. – icza Jan 15 '20 at 12:56
  • Thank you. I think bytes is an alias for uint8 in Go? I printed out reflect.TypeOf(itemArray[i])) and got uint8 for those long numbers coming from the GetTopStories() API. – mangokitty Jan 15 '20 at 13:03
  • 2
    Yes, `byte` is an alias for `uint8`. Your `MakeHTTPRequest()` returns a `[]byte`, so indexing it will result in `byte` values. But this is the HTTP response, not the individual item IDs. – icza Jan 15 '20 at 13:04

1 Answers1

1

itemArray, _ := MakeHTTPRequest(url)

itemArray must be unmarshaled like

dat := make([]uint64, 0)
if err := json.Unmarshal(itemArray, &dat); err != nil {
        panic(err)
}
Maxim
  • 2,233
  • 6
  • 16
  • How does the UnMarshal help in this situation if after the unmarshalling, the type of itemArray is ```[]uint8``` again? Does this mean the representation of itemArray (the object that was used for storage or transmission) isn't transformed to a representation of the object that is executable – mangokitty Jan 15 '20 at 13:27
  • 1
    itemArray is wrong name for this var. in fact it is jsonResponse. you could check it by fmt.Println(string(itemArray)). So json.Unmarshal just transporting JSON data to var dat. and schema of this data import takes from declared type dat := make([]uint64, 0) – Maxim Jan 15 '20 at 13:30
  • Thank you! ```fmt.Println(string(itemArray[i])) ``` prints out an item as expected ```{"by":"pc","descendants":0,"id":91,"kids":[454519],"score":5,"time":1171908063,"title":"SunRocket cofounders up and leave","type":"story","url":"http://www.washingtonpost.com/wp-dyn/content/article/2007/02/11/AR2007021101198.html?nav=rss_technology"}```. When I try convert this into my defined ```Item``` struct using ```json.Unmarshal(jsonItem, &item)``` I get ```{ 0 0 [] 0 {0 0 }``` Do you know what this is about? – mangokitty Jan 15 '20 at 13:45
  • 1
    you Item struct has only private fields that is the reason. you need use UpperCase for first letter of fields name – Maxim Jan 15 '20 at 14:51