6 Create a package redditnews

All .go files must declare the package that they belong to as the first line of the file excluding whitespace and comments. Packages are contained in a single directory. All .go files in a single directory must declare the same package name.

The convention for naming your package is to use the name of the directory containing it. This has the benefit of making it clear what the package name is when you import it.

Each folder represents a package. Each package is a unit of code that gets compiled into a static library. When a main function exists, then these packages are linked together, along with the runtime, to create an executable program.

Change redditnews.go (remember that we don’t need to import log here) to the following:

Program redditnews.go


package redditnews

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
)

type Item struct {
	Author string `json:"author"`
	Score  int    `json:"score"`
	URL    string `json:"url"`
	Title  string `json:"title"`
}

type response struct {
        Data1 struct {
                Children []struct {
                        Data2 Item `json:"data"`
                } `json:"children"`
        } `json:"data"`
}

func Get(reddit string) ([]Item, error) {
        url := fmt.Sprintf("http://reddit.com/r/%s.json", reddit)
	resp, err := http.Get(url)
	if err != nil {
	        return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
	        return nil, errors.New(resp.Status)
	}

	r := new(response)
	err = json.NewDecoder(resp.Body).Decode(r)
	if err != nil {
	        return nil, err
	}

	items := make([]Item, len(r.Data1.Children))
	for i, child := range r.Data1.Children {
	        items[i] = child.Data2
	}
	return items, nil
}

func (i Item) String() string {
	return fmt.Sprintf(
		"Author: %s\nScore: %d\nURL: %s\nTitle: %s\n\n",
		i.Author,
		i.Score,
		i.URL,
		i.Title)
}

Note that there is no main function in the code above. You can download this code here.

To confirm whether our package works, create a new folder inside your redditnews folder named say reddit, and copy the following program reddit.go file there.

Program reddit.go


package main

import (
	"fmt"
	"github.com/SatishTalim/redditnews"
	"log"
)

func main() {
	items, err := redditnews.Get("golang")
	if err != nil {
		log.Fatal(err)
	}

	for _, item := range items {
		fmt.Println(item)
	}
}

You can download this code here.

Remember to import the redditnews package, and use the redditnews. prefix before the Get invocation.

redditnews is the name of the library and reddit below as that of the command-line client.

Run reddit.go to confirm that our package works.