mastodon

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: BSD-3-Clause Imports: 10 Imported by: 0

README

go-mastodon/mastodon

mastodon

CI Go Reference

A pure-Go, dependency-free read client for the Mastodon REST API.

  • CGO_ENABLED=0 — no C, static binaries everywhere.
  • Zero third-party dependencies — standard library only.
  • Reads public, hashtag and per-account timelines, with Link-header pagination.
  • 100% test coverage, network-free tests via net/http/httptest.

Install

go get github.com/go-mastodon/mastodon

Requires Go 1.26.4 or newer.

Usage

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/go-mastodon/mastodon"
)

func main() {
	c := mastodon.New("https://mastodon.social",
		mastodon.WithUserAgent("myapp/1.0"),
		// mastodon.WithToken("…"), // optional bearer token
	)

	tl, err := c.PublicTimeline(context.Background(), mastodon.TimelineOptions{
		Limit:     20,
		OnlyMedia: true,
		Local:     true,
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, s := range tl.Statuses {
		fmt.Printf("@%s: %s\n", s.Account.Acct, s.URL)
	}

	// Fetch the next page using the pagination cursor.
	if tl.MaxID != "" {
		next, err := c.PublicTimeline(context.Background(), mastodon.TimelineOptions{MaxID: tl.MaxID})
		if err != nil {
			log.Fatal(err)
		}
		_ = next
	}
}
Other timelines
// A hashtag timeline.
tl, err := c.HashtagTimeline(ctx, "golang", mastodon.TimelineOptions{Limit: 10})

// An account's statuses (resolves the acct to an account ID first).
tl, err := c.AccountStatuses(ctx, "Gargron@mastodon.social", mastodon.TimelineOptions{})

API

Method Endpoint
PublicTimeline GET /api/v1/timelines/public
HashtagTimeline GET /api/v1/timelines/tag/:hashtag
AccountStatuses GET /api/v1/accounts/lookup then GET /api/v1/accounts/:id/statuses

All methods take a context.Context and TimelineOptions (Limit, MaxID, OnlyMedia, Local) and return a *Timeline whose MaxID field carries the rel="next" pagination cursor parsed from the Link response header.

License

BSD-3-Clause. See LICENSE.

Documentation

Overview

Package mastodon is a dependency-free read client for the Mastodon REST API.

It uses only the Go standard library (CGO_ENABLED=0) and exposes a small surface for reading public, hashtag and per-account timelines.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	ID             string `json:"id"`
	Username       string `json:"username"`
	Acct           string `json:"acct"`
	DisplayName    string `json:"display_name"`
	URL            string `json:"url"`
	Avatar         string `json:"avatar"`
	Note           string `json:"note"` // HTML bio
	FollowersCount int    `json:"followers_count"`
}

Account is a Mastodon account.

type Client

type Client struct {
	// Instance is the base URL of the Mastodon instance,
	// e.g. https://mastodon.social.
	Instance string
	// Token is an optional bearer token. When set, requests are
	// authenticated with an Authorization header.
	Token string
	// HTTPClient is the underlying HTTP client. When nil, http.DefaultClient
	// is used.
	HTTPClient *http.Client
	// UserAgent is the value sent in the User-Agent header.
	UserAgent string
}

Client is a read-only Mastodon REST API client.

func New

func New(instance string, opts ...Option) *Client

New creates a Client for the given instance base URL.

func (*Client) AccountStatuses

func (c *Client) AccountStatuses(ctx context.Context, acct string, opts TimelineOptions) (*Timeline, error)

AccountStatuses resolves acct via GET /api/v1/accounts/lookup and then fetches that account's statuses (GET /api/v1/accounts/:id/statuses).

func (*Client) Following added in v0.2.0

func (c *Client) Following(ctx context.Context, accountID string, opts TimelineOptions) (*FollowingPage, error)

Following fetches one page of the accounts that accountID follows (GET /api/v1/accounts/:id/following). Feed the returned FollowingPage.MaxID back through TimelineOptions.MaxID to page the rest. A bearer token authenticates the request (required when the target hides their follows); a public follows list is readable anonymously.

func (*Client) HashtagTimeline

func (c *Client) HashtagTimeline(ctx context.Context, tag string, opts TimelineOptions) (*Timeline, error)

HashtagTimeline fetches the timeline for a hashtag (GET /api/v1/timelines/tag/:hashtag).

func (*Client) HomeTimeline added in v0.2.0

func (c *Client) HomeTimeline(ctx context.Context, opts TimelineOptions) (*Timeline, error)

HomeTimeline fetches the authenticated user's home timeline — the statuses from the accounts they follow (GET /api/v1/timelines/home). A bearer token is required; without one the instance returns 401.

func (*Client) PublicTimeline

func (c *Client) PublicTimeline(ctx context.Context, opts TimelineOptions) (*Timeline, error)

PublicTimeline fetches the public timeline (GET /api/v1/timelines/public).

func (*Client) SearchAccounts added in v0.3.0

func (c *Client) SearchAccounts(ctx context.Context, q string, limit int) ([]Account, error)

SearchAccounts returns the accounts matching q via GET /api/v2/search (type=accounts) — used to discover accounts to follow. It reads the "accounts" slice of the search result and ignores statuses/hashtags. limit caps the page (0 = server default). A token is not required on most instances for account search, but one (via WithToken) broadens the results (remote resolution).

func (*Client) VerifyCredentials added in v0.2.0

func (c *Client) VerifyCredentials(ctx context.Context) (*Account, error)

VerifyCredentials fetches the account associated with the configured bearer token (GET /api/v1/accounts/verify_credentials), returning at least its ID — the handle a caller needs to then page the account's own Client.Following list. A bearer token is required; without one the instance returns 401.

type FollowingPage added in v0.2.0

type FollowingPage struct {
	Accounts []Account
	MaxID    string
}

FollowingPage is one page of the accounts a target follows, plus the pagination cursor. MaxID is parsed from the Link header's rel="next" URL and passed back via TimelineOptions.MaxID to fetch the following page; it is empty when the list is exhausted. Mastodon keys following pagination on an internal relationship id it exposes only through the Link header, so the cursor is opaque and must be round-tripped rather than derived from an account id.

type Media

type Media struct {
	Type        string `json:"type"` // image, video, gifv, audio
	URL         string `json:"url"`
	PreviewURL  string `json:"preview_url"`
	Description string `json:"description"`
}

Media is a media attachment on a status.

type Option

type Option func(*Client)

Option configures a Client.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient sets the HTTP client used to perform requests.

func WithToken

func WithToken(t string) Option

WithToken sets the bearer token used to authenticate requests.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header value.

type Status

type Status struct {
	ID          string    `json:"id"`
	URL         string    `json:"url"`
	Content     string    `json:"content"` // HTML
	CreatedAt   time.Time `json:"created_at"`
	Account     Account   `json:"account"`
	Favourites  int       `json:"favourites_count"`
	Reblogs     int       `json:"reblogs_count"`
	Replies     int       `json:"replies_count"`
	Sensitive   bool      `json:"sensitive"`
	SpoilerText string    `json:"spoiler_text"`
	Media       []Media   `json:"media_attachments"`
	Tags        []Tag     `json:"tags"`
}

Status is a Mastodon status (toot).

type Tag

type Tag struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

Tag is a hashtag referenced by a status.

type Timeline

type Timeline struct {
	Statuses []Status
	// MaxID is extracted from the Link header rel="next" and can be passed
	// as TimelineOptions.MaxID to fetch the following page. It is empty when
	// there is no next page.
	MaxID string
}

Timeline is a page of statuses plus the pagination cursor.

type TimelineOptions

type TimelineOptions struct {
	Limit     int
	MaxID     string
	OnlyMedia bool
	Local     bool
}

TimelineOptions holds the query parameters shared by the timeline methods.

Jump to

Keyboard shortcuts

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