An open API service indexing awesome lists of open source software.

https://github.com/piszmog/hnclient

Go client for Hacker News API
https://github.com/piszmog/hnclient

go hackernews-api

Last synced: 7 months ago
JSON representation

Go client for Hacker News API

Awesome Lists containing this project

README

          

# Hacker News API Client for Go

[![CI](https://github.com/Piszmog/hnclient/workflows/CI/badge.svg)](https://github.com/Piszmog/hnclient/actions)
[![Go Report Card](https://goreportcard.com/badge/github.com/Piszmog/hnclient)](https://goreportcard.com/report/github.com/Piszmog/hnclient)
[![GoDoc](https://godoc.org/github.com/Piszmog/hnclient?status.svg)](https://godoc.org/github.com/Piszmog/hnclient)

A comprehensive, type-safe Go client for the [Hacker News API](https://github.com/HackerNews/API).

## Installation

```bash
go get github.com/Piszmog/hnclient
```

## Quick Start

```go
package main

import (
"context"
"fmt"
"net/http"
"time"

"github.com/Piszmog/hnclient"
)

func main() {
// Create client with timeout
httpClient := &http.Client{Timeout: 10 * time.Second}
client := hnclient.New(httpClient, hnclient.URLV0)

// Get top stories
ctx := context.Background()
stories, err := client.GetTopStories(ctx)
if err != nil {
panic(err)
}

// Get first story details
if len(stories) > 0 {
item, err := client.GetItem(ctx, stories[0])
if err != nil {
panic(err)
}
fmt.Printf("Top story ID: %d\n", item.GetID())
}
}
```

## Advanced Usage

### Custom HTTP Client

You can provide your own HTTP client with custom settings:

```go
httpClient := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
},
}
client := hnclient.New(httpClient, hnclient.URLV0)
```

## Item Types

The client supports all Hacker News item types:

- **Story** - News stories and links that appear on the front page
- **Comment** - User comments on stories or other comments
- **Job** - Job postings from the Jobs section
- **Poll** - Poll questions with multiple choice options
- **PollOption** - Individual choices within a poll

All items implement the `Item` interface and can be type-asserted to their specific types for accessing additional fields.

### Type Assertions

```go
item, err := client.GetItem(ctx, itemID)
if err != nil {
return err
}

switch v := item.(type) {
case hnclient.Story:
fmt.Printf("Story: %s\n", v.Title)
case hnclient.Comment:
fmt.Printf("Comment by: %s\n", v.By)
case hnclient.Job:
fmt.Printf("Job: %s\n", v.Title)
case hnclient.Poll:
fmt.Printf("Poll: %s\n", v.Title)
case hnclient.PollOption:
fmt.Printf("Poll option: %s\n", v.Text)
}
```