GoHN — Hacker News API Wrapper for Go

Go Reference

GoHN is a wrapper for the Hacker News API for Go.

It facilitates the use of the API by providing a simple interface to the API endpoints.

Features 🚀

  • Get the top/new/best/ask/show/job stories
  • Retrieve all comments (with metadata) for a story using goroutines to speed up the process
  • Retrieve the comments ordered as they appear in the story on the website
  • Apply filters to retrieved items (stories, comments)
  • Can be used with a custom http client (for instance, to use a proxy)

Usage 💻

Refer to the GoDoc for the full API reference.

Example

Refer to example/main.go for a full example on how to retrieve the top stories’ IDs and the all the comments for the first one.

	// Instantiate a new client to retrieve data from the Hacker News API
	hn := gohn.NewDefaultClient()

	// Get the top 500 stories' IDs
	topStoriesIds, _ := hn.GetTopStoriesIDs()

	// Retrieve the details of the first one
	story, _ := hn.GetItem(topStoriesIds[0])

	// Print the story's title
	fmt.Println("Title:", story.Title)

	// Print the story's author
	fmt.Println("Author:", story.By)

	// Print the story's score
	fmt.Println("Score:", story.Score)

	// Print the story's URL
	fmt.Println("URL:", story.URL)

	fmt.Println()
	fmt.Println()

	// Retrieve all the comments for that story
	// UnescapeHTML is applied to each retrieved item to unescape HTML characters
	commentsMap := hn.RetrieveKidsItems(story, processors.UnescapeHTML())

	fmt.Printf("Comments found: %d\n", len(commentsMap))
	fmt.Println()

	// Create a Story struct to hold the story and its comments
	storyWithComments := gohn.Story{
		StoryItem:       story,
		CommentsByIdMap: commentsMap,
	}

	// Calculate the position of each comment in the story
	storyWithComments.SetCommentsPosition()

	// Get an ordered list of comments' IDs (ordered by position)
	orderedIDs := storyWithComments.GetOrderedCommentsIDs()

	// Print the comments
	for _, id := range orderedIDs {
		comment := commentsMap[id]
		fmt.Println(comment.Text)
		fmt.Println()
	}

Contributing 🤝🏼

Feel free to fork this repo and create a PR. I will review them and merge, if ok.

License 📝

MIT

GitHub

View Github