hn

package module
v0.0.0-...-9bfcfdc Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2015 License: MIT Imports: 5 Imported by: 3

README

hn

Go library for the Hacker News API

This fork consists of ask, jobs & show stories which is not present on the original repo currently.

Installation

# original
go get -u github.com/peterhellberg/hn

OR

go get -u github.com/aacanakin/hn

Services

The client currently delegates to implementations of three interfaces: ItemsService, LiveService and UsersService.

Example usage

Showing the current top ten stories

package main

import (
  "fmt"

  "github.com/peterhellberg/hn"
)

func main() {
  // NewClient returns a new Hacker News API client.
  // If httpClient is nil, http.DefaultClient is used.
  hn := hn.NewClient(nil)

  ids, err := hn.TopStories()
  if err != nil {
    panic(err)
  }

  for i, id := range ids[:10] {
    item, err := hn.Item(id)
    if err != nil {
      panic(err)
    }

    fmt.Println(i, "–", item.Title, "\n   ", item.URL, "\n")
  }
}

Showing the current top ten stories using goroutines, a channel and a wait group

package main

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

  "github.com/peterhellberg/hn"
)

type indexItem struct {
  Index int
  Item  *hn.Item
}

var (
  items    = map[int]*hn.Item{}
  messages = make(chan indexItem)
)

func main() {
  hn := hn.NewClient(&http.Client{
    Timeout: time.Duration(5 * time.Second),
  })

  ids, err := hn.TopStories()
  if err != nil {
    panic(err)
  }

  go func() {
    for i := range messages {
      items[i.Index] = i.Item
    }
  }()

  var wg sync.WaitGroup

  for i, id := range ids[:10] {
    wg.Add(1)
    go func(i, id int) {
      defer wg.Done()

      item, err := hn.Item(id)
      if err != nil {
        panic(err)
      }

      messages <- indexItem{i, item}
    }(i, id)
  }

  wg.Wait()

  for i := 0; i < 10; i++ {
    fmt.Println(i, "–", items[i].Title, "\n   ", items[i].URL, "\n")
  }
}

Showing information about a given user (first argument)

package main

import (
  "fmt"
  "os"

  "github.com/peterhellberg/hn"
)

func main() {
  if len(os.Args) < 2 {
    return
  }

  if u, err := hn.NewClient(nil).User(os.Args[1]); err == nil {
    fmt.Println("ID:   ", u.ID)
    fmt.Println("About:", u.About)
    fmt.Println("Karma:", u.Karma)
  }
}

License (MIT)

Copyright (c) 2014-2015 Peter Hellberg

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	STORY_TYPE_NEW  = "new"
	STORY_TYPE_TOP  = "top"
	STORY_TYPE_JOB  = "job"
	STORY_TYPE_ASK  = "ask"
	STORY_TYPE_SHOW = "show"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Items ItemsService
	Users UsersService
	Live  LiveService

	// BaseURL is the base url for Hacker News API.
	BaseURL *url.URL

	// User agent used for HTTP requests to Hacker News API.
	UserAgent string
	// contains filtered or unexported fields
}

A Client communicates with the Hacker News API.

func NewClient

func NewClient(httpClient *http.Client) *Client

NewClient returns a new Hacker News API client. If httpClient is nil, http.DefaultClient is used.

func (*Client) AskStories

func (c *Client) AskStories() ([]int, error)

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error)

Do sends an API request and returns the API response. The API response is decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred.

func (*Client) Item

func (c *Client) Item(id int) (*Item, error)

Item is a convenience method proxying Items.Get

func (*Client) JobStories

func (c *Client) JobStories() ([]int, error)

func (*Client) MaxItem

func (c *Client) MaxItem() (int, error)

MaxItem is a convenience method proxying Live.MaxItem

func (*Client) NewRequest

func (c *Client) NewRequest(s string) (*http.Request, error)

NewRequest creates an API request.

func (*Client) NewStories

func (c *Client) NewStories() ([]int, error)

func (*Client) ShowStories

func (c *Client) ShowStories() ([]int, error)

func (*Client) TopStories

func (c *Client) TopStories() ([]int, error)

func (*Client) Updates

func (c *Client) Updates() (*Updates, error)

Updates is a convenience method proxying Live.Updates

func (*Client) User

func (c *Client) User(id string) (*User, error)

User is a convenience method proxying Users.Get

type Item

type Item struct {
	ID        int    `json:"id" bson:"_id"`
	Parent    int    `json:"parent" bson:"parent"`
	Kids      []int  `json:"kids" bson:"kids"`
	Parts     []int  `json:"parts" bson:"parts"`
	Score     int    `json:"score" bson:"score"`
	Timestamp int    `json:"time" bson:"time"`
	By        string `json:"by" bson:"by"`
	Type      string `json:"type" bson:"type"`
	Title     string `json:"title" bson:"title"`
	Text      string `json:"text" bson:"text"`
	URL       string `json:"url" bson:"url"`
	Dead      bool   `json:"dead" bson:"dead"`
	Deleted   bool   `json:"deleted" bson:"deleted"`
}

Item represents a item

func (*Item) Time

func (i *Item) Time() time.Time

Time return the time of the timestamp

type ItemsService

type ItemsService interface {
	Get(id int) (*Item, error)
}

ItemsService communicates with the news related endpoints in the Hacker News API

type LiveService

type LiveService interface {
	GetStories(string) ([]int, error)

	MaxItem() (int, error)
	Updates() (*Updates, error)
}

LiveService communicates with the news related endpoints in the Hacker News API

type Updates

type Updates struct {
	Items    []int    `json:"items"`
	Profiles []string `json:"profiles"`
}

Updates contains the latest updated items and profiles

type User

type User struct {
	About     string `json:"about"`
	Created   int    `json:"created"`
	Delay     int    `json:"delay"`
	ID        string `json:"id"`
	Karma     int    `json:"karma"`
	Submitted []int  `json:"submitted"`
}

User represents a Hacker News user

func (*User) CreatedTime

func (u *User) CreatedTime() time.Time

CreatedTime return the time of the created

type UsersService

type UsersService interface {
	Get(id string) (*User, error)
}

UsersService communicates with the news related endpoints in the Hacker News API

Jump to

Keyboard shortcuts

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