github.com/wtfutil/wtf@v0.43.0/modules/hackernews/client.go (about)

     1  package hackernews
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"strconv"
     9  	"strings"
    10  
    11  	"github.com/wtfutil/wtf/utils"
    12  )
    13  
    14  func GetStories(storyType string) ([]int, error) {
    15  	var storyIds []int
    16  
    17  	switch strings.ToLower(storyType) {
    18  	case "new", "top", "job", "ask":
    19  		resp, err := apiRequest(storyType + "stories")
    20  		if err != nil {
    21  			return storyIds, err
    22  		}
    23  
    24  		err = utils.ParseJSON(&storyIds, bytes.NewReader(resp))
    25  		if err != nil {
    26  			return storyIds, err
    27  		}
    28  	}
    29  
    30  	return storyIds, nil
    31  }
    32  
    33  func GetStory(id int) (Story, error) {
    34  	var story Story
    35  
    36  	resp, err := apiRequest("item/" + strconv.Itoa(id))
    37  	if err != nil {
    38  		return story, err
    39  	}
    40  
    41  	err = utils.ParseJSON(&story, bytes.NewReader(resp))
    42  	if err != nil {
    43  		return story, err
    44  	}
    45  
    46  	return story, nil
    47  }
    48  
    49  /* -------------------- Unexported Functions -------------------- */
    50  
    51  var (
    52  	apiEndpoint = "https://hacker-news.firebaseio.com/v0/"
    53  )
    54  
    55  func apiRequest(path string) ([]byte, error) {
    56  	req, err := http.NewRequest("GET", apiEndpoint+path+".json", http.NoBody)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	httpClient := &http.Client{}
    62  	resp, err := httpClient.Do(req)
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  
    67  	defer func() { _ = resp.Body.Close() }()
    68  
    69  	if resp.StatusCode < 200 || resp.StatusCode > 299 {
    70  		return nil, fmt.Errorf(resp.Status)
    71  	}
    72  
    73  	body, err := io.ReadAll(resp.Body)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	return body, nil
    78  }