8 Documenting redditnews

Godoc is the Go documentation tool. It reads documentation directory from Go source files. It’s easy to keep documentation and code in sync when they live together in the same place.

Here’s our redditnews package when viewed from godoc on the command line:

godoc output

godoc output

To document add a comment directly above their declarations:

// Item describes a RedditNews item.
type Item struct {

// Get fetches the most recent Items posted to the specified subreddit.
func Get(reddit string) ([]Item, error){

Most importantly, document the package itself by adding a comment to the package clause:

// redditnews package implements a basic client for the Reddit API.
package redditnews

Don’t worry about documenting the String method, as all Go programmers should be familiar with it and its purpose.

The godoc output for our revised package:

godoc output

godoc output

The modified redditnews.go file is:

Program redditnews.go


// redditnews package implements a basic client for the Reddit API.
package redditnews

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

// Item describes a RedditNews item.
type Item struct {
	Author string `json:"author"`
	Score  int    `json:"score"`
	URL    string `json:"url"`
	Title  string `json:"title"`
}

type response struct {
	Data struct {
		Children []struct {
			Data Item
		}
	}
}

// Get fetches the most recent Items posted to the specified subreddit.
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.Data.Children))
	for i, child := range r.Data.Children {
		items[i] = child.Data
	}
	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)
}

// Email prepares the body of an email
func Email() string {
	var buffer bytes.Buffer

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

	// Need to build strings from items
	for _, item := range items {
		buffer.WriteString(item.String())
	}

	return buffer.String()
}

You can download this code here.

8.1 References