hn

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2025 License: MIT Imports: 11 Imported by: 0

README

API Client for Hacker News

Links:

Features:

  • Retrieve user data (comments, stories, etc.)
  • Fetch recent updates and news (Best, New, etc.)
  • Filter and sort the results by multiple fields

Installation

go get -u github.com/imotkin/hn-client

Examples

Import the library and create a client
import (
    "github.com/imotkin/hn-client"
)

func main() {
    client := hn.NewClient(nil)
    
    // Set a limit on the number of workers
    hn.SetMaxWorkers(10)

    ctx := context.Background()
}
Fetch user data (comments, stories, or custom items)
comments, _ := client.Users.Comments(ctx, "johndoe")

stories, _ := client.Users.Stories(ctx, "johndoe")

items, _ := client.Users.Items(ctx, "johndoe", func (i hn.Item) bool {
    return i.Type == hn.CommentType && strings.Contains(i.Title, "Go")
})
Fetch a list of items with a filter
items, _ := client.Items.List(ctx, []uint{1, 2, 3}, func (i hn.Item) bool {
    return i.Type == hn.CommentType && strings.Contains(i.Title, "Go")
})

// Convert to a slice of comments
comments := hn.ToList[hn.Comment](items)

for _, comment := range comments {
    fmt.Println(comment.ID, comment.Text)
}
Sort items by predefined fields (id, time, score, or type)
hn.SortScore(comments, hn.Ascending)

hn.SortTime(stories, hn.Descending)
Sort items by your custom order
hn.Sort(comments, func(a, b hn.Comment) int {
    return cmp.Compare(a.Text, b.Text)
})

hn.Sort(stories, func(a, b hn.Story) int {
    return cmp.Compare(a.By, b.By)
})
Fetch recent updates and news
recent, _ := client.Live.Recent(context.Background(), 10)

updates, _ := client.Live.UpdateList(ctx, nil)

best, _ := client.Live.BestList(ctx, func (i hn.Item) bool {
    return strings.Contains(i.Title, "Go")
})

License

MIT License

Documentation

Index

Constants

View Source
const (
	StoryType      = "story"
	CommentType    = "comment"
	AskType        = "ask"
	JobType        = "job"
	PollType       = "poll"
	PollOptionType = "pollopt"
)

Variables

View Source
var (
	ErrNotFound = errors.New("item is not found")
)

Functions

func Fetch

func Fetch[T any](ctx context.Context, client *http.Client, method, url string) (T, error)

Fetch sends an HTTP request to the Hacker News API and returns a value of the specified type.

func SetMaxWorkers

func SetMaxWorkers(n int)

SetMaxWorkers sets the maximum number of workers for multiple item fetch operations. The default value of maxWorkers is -1, meaning there is no limit to the number of workers.

func Sort

func Sort[S Sortable](items []S, sort func(a, b S) int)

Sort sorts the items using the specified sorting function.

func SortID

func SortID[S Sortable](items []S, order Order)

SortID sorts the items by ID according to the specified order.

func SortScore

func SortScore[S Sortable](items []S, order Order)

SortScore sorts the items by score according to the specified order.

func SortTime

func SortTime[S Sortable](items []S, order Order)

SortTime sorts the items by creation time according to the specified order.

func SortType

func SortType[S Sortable](items []S, order Order)

SortType sorts the items by type according to the specified order.

func To

func To[C Convertible](item Item) (c C, err error)

To is a helper function to convert any Item struct to a struct of a specific type that implements the Convertible interface: Comment, Story, Ask, Job, Poll or PollOption. Another alternative for this function is a specific converter (ToComment, ToStory, etc.).

func ToList

func ToList[C Convertible](items []Item) []C

ToList converts a slice of items to a list of structs of a specific type.

If the type of any item doesn't match the output type, the item is excluded from the converted list.

Types

type Ask

type Ask struct {
	Descendants int    `json:"descendants,omitempty"`
	Kids        []uint `json:"kids,omitempty"`
	Text        string `json:"text,omitempty"`
	Title       string `json:"title,omitempty"`
	// contains filtered or unexported fields
}

func ToAsk

func ToAsk(item Item) Ask

ToAsk converts an Item struct to an Ask struct.

func (Ask) Type

func (a Ask) Type() string

type Client

type Client struct {
	Items *ItemService
	Users *UserService
	Live  *LiveService
}

Client represents a client for the Hacker News API.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient returns a new Hacker News API client. If httpClient is nil, the default client will be used.

type Comment

type Comment struct {
	Kids   []uint `json:"kids,omitempty"`
	Parent uint   `json:"parent,omitempty"`
	Text   string `json:"text,omitempty"`
	// contains filtered or unexported fields
}

func ToComment

func ToComment(item Item) Comment

ToComment converts an Item struct to a Comment struct.

func (Comment) Type

func (c Comment) Type() string

type Convertible

type Convertible interface {
	Type() string
}

Convertible describes types that can be converted from an Item.

type Item

type Item struct {
	Descendants int    `json:"descendants,omitempty"`
	Parts       []uint `json:"parts,omitempty"`
	Parent      uint   `json:"parent,omitempty"`
	Kids        []uint `json:"kids,omitempty"`
	Text        string `json:"text,omitempty"`
	Title       string `json:"title,omitempty"`
	Poll        uint   `json:"poll,omitempty"`
	URL         string `json:"url,omitempty"`
	// contains filtered or unexported fields
}

Item is a common type for all other types: story, comment, poll, etc. It contains all fields, so some of them may be empty if the value of the specific type doesn't have that field.

type ItemService

type ItemService struct {
	// contains filtered or unexported fields
}

ItemService provides methods to retrieve data about Hacker News items.

func (*ItemService) Get

func (s *ItemService) Get(ctx context.Context, id uint) (Item, error)

Get return an Item with the specified ID.

func (*ItemService) List

func (s *ItemService) List(ctx context.Context, ids []uint, filter func(Item) bool) ([]Item, error)

List returns a list of items with specific IDs, filtered if necessary.

type Job

type Job struct {
	Text  string `json:"text,omitempty"`
	Title string `json:"title,omitempty"`
	URL   string `json:"url,omitempty"`
	// contains filtered or unexported fields
}

func ToJob

func ToJob(item Item) Job

ToJob converts an Item struct to a Job struct.

func (Job) Type

func (j Job) Type() string

type LiveService

type LiveService struct {
	// contains filtered or unexported fields
}

LiveService provides methods to retrieve data about recent updates.

func (*LiveService) Ask

func (s *LiveService) Ask(ctx context.Context) ([]uint, error)

Ask returns a list of IDs for the asks.

func (*LiveService) AskList

func (s *LiveService) AskList(ctx context.Context, filter func(Item) bool) ([]Ask, error)

AskList returns a list of items for the asks, filtered if necessary.

func (*LiveService) Best

func (s *LiveService) Best(ctx context.Context) ([]uint, error)

Best returns a list of IDs for the best stories.

func (*LiveService) BestList

func (s *LiveService) BestList(ctx context.Context, filter func(Item) bool) ([]Item, error)

BestList returns a list of items for the best stories, filtered if necessary.

func (*LiveService) Job

func (s *LiveService) Job(ctx context.Context) ([]uint, error)

Job returns a list of IDs for the jobs.

func (*LiveService) JobList

func (s *LiveService) JobList(ctx context.Context, filter func(Item) bool) ([]Job, error)

JobList returns a list of items for the jobs, filtered if necessary.

func (*LiveService) MaxID

func (s *LiveService) MaxID(ctx context.Context) (uint, error)

MaxID returns the ID of the most recently published item.

func (*LiveService) New

func (s *LiveService) New(ctx context.Context) ([]uint, error)

New returns a list of IDs for the new stories.

func (*LiveService) NewList

func (s *LiveService) NewList(ctx context.Context, filter func(Item) bool) ([]Item, error)

NewList returns a list of items for the new stories, filtered if necessary.

func (*LiveService) Recent

func (s *LiveService) Recent(ctx context.Context, offset uint) ([]Item, error)

Recent returns the latest items with the given offset.

func (*LiveService) Show

func (s *LiveService) Show(ctx context.Context) ([]uint, error)

Show returns a list of IDs for the shows.

func (*LiveService) ShowList

func (s *LiveService) ShowList(ctx context.Context, filter func(Item) bool) ([]Story, error)

ShowList returns a list of items for the shows, filtered if necessary.

func (*LiveService) Top

func (s *LiveService) Top(ctx context.Context) ([]uint, error)

Top returns a list of IDs for the top stories.

func (*LiveService) TopList

func (s *LiveService) TopList(ctx context.Context, filter func(Item) bool) ([]Item, error)

TopList returns a list of items for the top stories, filtered if necessary.

func (*LiveService) Update

func (s *LiveService) Update(ctx context.Context) (Update, error)

Update returns an Update containing IDs of updated items and profiles.

func (*LiveService) UpdateList

func (s *LiveService) UpdateList(ctx context.Context, filter func(Item) bool) ([]Item, error)

UpdateList returns a list of updated items, filtered if necessary.

type Order

type Order int

Order represents the sorting order: ascending or descending.

const (
	Ascending Order = iota
	Descending
)

type Poll

type Poll struct {
	Descendants int    `json:"descendants,omitempty"`
	Kids        []uint `json:"kids,omitempty"`
	Parts       []uint `json:"parts,omitempty"`
	Text        string `json:"text,omitempty"`
	Title       string `json:"title,omitempty"`
	// contains filtered or unexported fields
}

func ToPoll

func ToPoll(item Item) Poll

ToPoll converts an Item struct to a Poll struct.

func (Poll) Type

func (p Poll) Type() string

type PollOption

type PollOption struct {
	Poll uint   `json:"poll,omitempty"`
	Text string `json:"text,omitempty"`
	// contains filtered or unexported fields
}

func ToPollOption

func ToPollOption(item Item) PollOption

ToPollOption converts an Item struct to a PollOption struct.

func (PollOption) Type

func (o PollOption) Type() string

type Sortable

type Sortable interface {
	// contains filtered or unexported methods
}

Sortable defines methods for comparing baseItem and other structs (e.g., Comment, Story, etc.).

type Story

type Story struct {
	Descendants int    `json:"descendants,omitempty"`
	Kids        []uint `json:"kids,omitempty"`
	Text        string `json:"text,omitempty"`
	Title       string `json:"title,omitempty"`
	URL         string `json:"url,omitempty"`
	// contains filtered or unexported fields
}

func ToStory

func ToStory(item Item) Story

ToStory converts an Item struct to a Story struct.

func (Story) Type

func (s Story) Type() string

type Timestamp

type Timestamp struct {
	time.Time
}

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(data []byte) error

type Update

type Update struct {
	Items    []uint   `json:"items,omitempty"`
	Profiles []string `json:"profiles,omitempty"`
}

type User

type User struct {
	ID        string    `json:"id,omitempty"`
	About     string    `json:"about,omitempty"`
	Created   Timestamp `json:"created,omitzero"`
	Karma     int       `json:"karma,omitempty"`
	Submitted []uint    `json:"submitted,omitempty"`
}

type UserService

type UserService struct {
	// contains filtered or unexported fields
}

UserService provides methods to retrieve data about Hacker News users.

func (*UserService) Asks

func (s *UserService) Asks(ctx context.Context, username string) ([]Ask, error)

Asks returns the asks submitted by the user with the given name.

func (*UserService) Comments

func (s *UserService) Comments(ctx context.Context, username string) ([]Comment, error)

Comments returns the comments submitted by the user with the given name.

func (*UserService) Get

func (s *UserService) Get(ctx context.Context, username string) (User, error)

Get returns a User with the given name.

func (*UserService) Items

func (s *UserService) Items(ctx context.Context, username string, filter func(Item) bool) ([]Item, error)

Items returns the items submitted by the user with the given name, filtered if necessary.

func (*UserService) Jobs

func (s *UserService) Jobs(ctx context.Context, username string) ([]Job, error)

Jobs returns the jobs submitted by the user with the given name.

func (*UserService) PollOptions

func (s *UserService) PollOptions(ctx context.Context, username string) ([]PollOption, error)

PollOptions returns the poll options submitted by the user with the given name.

func (*UserService) Polls

func (s *UserService) Polls(ctx context.Context, username string) ([]Poll, error)

Polls returns the polls submitted by the user with the given name.

func (*UserService) Stories

func (s *UserService) Stories(ctx context.Context, username string) ([]Story, error)

Stories returns the stories submitted by the user with the given name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL