Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Go CLI for Hacker News via the Algolia API. No auth required.

- `cmd/hn/main.go` -- thin entrypoint, version embedding via ldflags
- `internal/cmd/root.go` -- all CLI commands (cobra)
- `internal/api/client.go` -- HN Algolia API client
- `internal/api/client.go` -- HN Algolia and Firebase API client
- `internal/output/format.go` -- compact plaintext and JSON formatters
- `skills/hn/SKILL.md` -- agent skill definition

Expand All @@ -28,4 +28,5 @@ Go CLI for Hacker News via the Algolia API. No auth required.

## API

HN Algolia API at `https://hn.algolia.com/api/v1/`. Free, no auth, no rate limits.
HN Algolia API at `https://hn.algolia.com/api/v1/`, and the official Firebase API
at `https://hacker-news.firebaseio.com/v0/` for what Algolia lacks. Free, no auth.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed
- Exit codes now match the docs. Network failures, rate limits and server
errors exit 8, missing items and users exit 5, and an empty `hn front` exits 3.
- `hn status --json` exits 8 when the API is down.
- `hn user` looks profiles up through the Firebase API, because Algolia answers
500 for unknown users.

## [0.2.1] — 2026-08-08

### Fixed
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Agent-friendly CLI for [Hacker News](https://news.ycombinator.com) via the [Algo

- **Fast** — direct Algolia API, no scraping or HTML parsing
- **Agent-friendly** — `--json` on every command, structured exit codes, stderr-only progress
- **Zero config** — no API keys, no auth, no rate limits
- **Zero config** — no API keys, no auth
- **Single binary** — install via Homebrew, Scoop, or `go install`

<p align="center">
Expand Down Expand Up @@ -113,7 +113,7 @@ npx skills add -g voska/hn-cli

## API

Uses the [HN Algolia API](https://hn.algolia.com/api/v1/) -- free, public, no authentication or API keys required.
Uses the [HN Algolia API](https://hn.algolia.com/api/v1/) for search and threads, and the [official Firebase API](https://github.com/HackerNews/API) for user profiles. Both are free and public, with no authentication or API keys required.

## Output Modes

Expand Down Expand Up @@ -143,7 +143,7 @@ All commands support `--json`.
| 1 | error | General error |
| 3 | empty | No results found |
| 5 | not_found | Invalid ID or username |
| 8 | retryable | Transient error, safe to retry |
| 8 | retryable | Network failure, rate limit or server error, safe to retry |

## Development

Expand Down
119 changes: 63 additions & 56 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"encoding/json"
"errors"
"fmt"
"html"
"net/http"
Expand All @@ -11,28 +12,64 @@ import (
"time"
)

// BaseURL is the default HN Algolia API endpoint.
const BaseURL = "https://hn.algolia.com/api/v1"
const (
// BaseURL is the default HN Algolia API endpoint.
BaseURL = "https://hn.algolia.com/api/v1"
// FirebaseURL is the default official HN API endpoint.
FirebaseURL = "https://hacker-news.firebaseio.com/v0"
)

var (
// ErrNotFound means the requested item or user does not exist.
ErrNotFound = errors.New("not found")
// ErrRetryable means a network failure, rate limit or server error.
ErrRetryable = errors.New("temporary failure")
)

// Client wraps an HTTP client and base URL for the HN Algolia API.
// Client wraps an HTTP client and base URLs for the HN APIs.
type Client struct {
baseURL string
httpClient *http.Client
baseURL string
firebaseURL string
httpClient *http.Client
}

// NewClient returns a Client configured with the given base URL and HTTP client.
func NewClient(baseURL string, httpClient *http.Client) *Client {
return &Client{
baseURL: baseURL,
httpClient: httpClient,
baseURL: baseURL,
firebaseURL: FirebaseURL,
httpClient: httpClient,
}
}

// DefaultClient returns a Client using the production API and a 15s timeout.
// DefaultClient returns a Client using the production APIs and a 15s timeout.
func DefaultClient() *Client {
return NewClient(BaseURL, &http.Client{Timeout: 15 * time.Second})
}

// getJSON fetches reqURL and decodes the response into v.
func (c *Client) getJSON(reqURL string, v any) error {
resp, err := c.httpClient.Get(reqURL)
if err != nil {
return fmt.Errorf("%w: %v", ErrRetryable, err)
}
defer resp.Body.Close()

switch {
case resp.StatusCode == http.StatusNotFound:
return ErrNotFound
case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500:
return fmt.Errorf("%w: api returned %d", ErrRetryable, resp.StatusCode)
case resp.StatusCode != http.StatusOK:
return fmt.Errorf("api returned %d", resp.StatusCode)
}

if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
return fmt.Errorf("decode failed: %w", err)
}
return nil
}

// SearchResult represents the Algolia search response.
type SearchResult struct {
Hits []Hit `json:"hits"`
Expand Down Expand Up @@ -126,82 +163,52 @@ func (c *Client) BuildURL(opts SearchOptions) string {

// Search queries the HN Algolia search API.
func (c *Client) Search(opts SearchOptions) (*SearchResult, error) {
reqURL := c.BuildURL(opts)
resp, err := c.httpClient.Get(reqURL)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("api returned %d", resp.StatusCode)
}

var result SearchResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("decode failed: %w", err)
if err := c.getJSON(c.BuildURL(opts), &result); err != nil {
return nil, err
}
return &result, nil
}

// GetItem fetches a single item (story/comment) with its children.
func (c *Client) GetItem(id string) (*Item, error) {
reqURL := fmt.Sprintf("%s/items/%s", c.baseURL, id)
resp, err := c.httpClient.Get(reqURL)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("item %s not found", id)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("api returned %d", resp.StatusCode)
}

var item Item
if err := json.NewDecoder(resp.Body).Decode(&item); err != nil {
return nil, fmt.Errorf("decode failed: %w", err)
if err := c.getJSON(fmt.Sprintf("%s/items/%s", c.baseURL, url.PathEscape(id)), &item); err != nil {
return nil, fmt.Errorf("item %s: %w", id, err)
}
return &item, nil
}

// GetUser fetches a user profile.
// GetUser fetches a user profile. It uses the Firebase API because Algolia
// answers 500 for unknown users, which looks like an outage.
func (c *Client) GetUser(username string) (*User, error) {
reqURL := fmt.Sprintf("%s/users/%s", c.baseURL, url.PathEscape(username))
resp, err := c.httpClient.Get(reqURL)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
var profile *struct {
ID string `json:"id"`
About string `json:"about"`
Karma int `json:"karma"`
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("user %q not found", username)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("api returned %d", resp.StatusCode)
reqURL := fmt.Sprintf("%s/user/%s.json", c.firebaseURL, url.PathEscape(username))
if err := c.getJSON(reqURL, &profile); err != nil {
return nil, fmt.Errorf("user %s: %w", username, err)
}

var user User
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return nil, fmt.Errorf("decode failed: %w", err)
if profile == nil {
return nil, fmt.Errorf("user %s: %w", username, ErrNotFound)
}
return &user, nil
return &User{Username: profile.ID, About: profile.About, Karma: profile.Karma}, nil
}

// HealthCheck pings the API and returns latency.
func (c *Client) HealthCheck() (time.Duration, error) {
start := time.Now()
resp, err := c.httpClient.Get(c.baseURL + "/search?query=test&hitsPerPage=0")
if err != nil {
return 0, fmt.Errorf("api unreachable: %w", err)
return 0, fmt.Errorf("%w: %v", ErrRetryable, err)
}
defer resp.Body.Close()
elapsed := time.Since(start)

if resp.StatusCode != http.StatusOK {
return elapsed, fmt.Errorf("api returned %d", resp.StatusCode)
return elapsed, fmt.Errorf("%w: api returned %d", ErrRetryable, resp.StatusCode)
}
return elapsed, nil
}
Expand Down
81 changes: 71 additions & 10 deletions internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ package api

import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)

// testClient points both APIs at srv.
func testClient(srv *httptest.Server) *Client {
c := NewClient(srv.URL, srv.Client())
c.firebaseURL = srv.URL
return c
}

func TestBuildURL(t *testing.T) {
c := NewClient("https://example.com/api/v1", http.DefaultClient)

Expand Down Expand Up @@ -70,7 +78,7 @@ func TestSearch(t *testing.T) {
}))
defer srv.Close()

c := NewClient(srv.URL, srv.Client())
c := testClient(srv)
result, err := c.Search(SearchOptions{Query: "test"})
if err != nil {
t.Fatalf("Search() error: %v", err)
Expand All @@ -93,7 +101,7 @@ func TestGetItem(t *testing.T) {
}))
defer srv.Close()

c := NewClient(srv.URL, srv.Client())
c := testClient(srv)

item, err := c.GetItem("123")
if err != nil {
Expand All @@ -111,27 +119,80 @@ func TestGetItem(t *testing.T) {

func TestGetUser(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/users/pg" {
json.NewEncoder(w).Encode(User{Username: "pg", Karma: 157316})
if r.URL.Path == "/user/pg.json" {
w.Write([]byte(`{"id":"pg","karma":157316,"about":"Bug fixer."}`))
return
}
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("null"))
}))
defer srv.Close()

c := NewClient(srv.URL, srv.Client())
c := testClient(srv)

user, err := c.GetUser("pg")
if err != nil {
t.Fatalf("GetUser() error: %v", err)
}
if user.Username != "pg" {
t.Errorf("expected username 'pg', got %q", user.Username)
if user.Username != "pg" || user.Karma != 157316 || user.About != "Bug fixer." {
t.Errorf("unexpected user: %+v", user)
}

_, err = c.GetUser("nonexistent_user_xyz")
if err == nil {
t.Error("expected error for missing user")
if !errors.Is(err, ErrNotFound) {
t.Errorf("expected ErrNotFound for missing user, got %v", err)
}
}

func TestErrorClassification(t *testing.T) {
tests := []struct {
name string
status int
want error
}{
{"not found", http.StatusNotFound, ErrNotFound},
{"rate limited", http.StatusTooManyRequests, ErrRetryable},
{"server error", http.StatusBadGateway, ErrRetryable},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.status)
}))
defer srv.Close()

c := testClient(srv)
if _, err := c.GetItem("1"); !errors.Is(err, tt.want) {
t.Errorf("GetItem() error = %v, want %v", err, tt.want)
}
})
}
}

func TestNetworkFailureIsRetryable(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := srv.URL
srv.Close()

c := NewClient(url, http.DefaultClient)
c.firebaseURL = url
if _, err := c.GetItem("1"); !errors.Is(err, ErrRetryable) {
t.Errorf("GetItem() error = %v, want ErrRetryable", err)
}
if _, err := c.Search(SearchOptions{Query: "go"}); !errors.Is(err, ErrRetryable) {
t.Errorf("Search() error = %v, want ErrRetryable", err)
}
}

func TestClientErrorIsNotRetryable(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}))
defer srv.Close()

c := testClient(srv)
if _, err := c.Search(SearchOptions{Query: "go"}); err == nil || errors.Is(err, ErrRetryable) {
t.Errorf("Search() error = %v, want a non-retryable error", err)
}
}

Expand Down
Loading
Loading