telegraph

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 18 Imported by: 3 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

telegraph-go

Go library for using Telegraph API.

Install

$ go get -u github.com/meinside/telegraph-go

Usage

ctx := context.Background()

// new account (keep client.AccessToken() to reuse it later with telegraph.Load)
client, err := telegraph.Create(ctx, telegraph.CreateAccountParams{ShortName: "my-blog"})

// publish HTML; unsupported tags and attributes are filtered out
page, err := client.CreatePageWithHTML(ctx, telegraph.CreatePageParams{Title: "Hello"}, "<p>Hello, <b>world</b></p>")

// fetched content decodes to string / telegraph.NodeElement and can be sent back as is
page, err = client.GetPage(ctx, page.Path, true)
html, err := telegraph.NodesToHTML(page.Content)
  • Options: WithHTTPClient, WithBaseURL, WithLogger (see telegraph.go).
  • Errors: *APIError (with FloodWait()), *HTTPError, and ErrInvalidParameter for parameters rejected before sending (see errors.go).

More in ./samples/.

Test

$ go test -short ./...   # offline tests only
$ go test ./...          # also TestLiveAPI: creates an account and pages on telegra.ph

Todo

  • Add a helper function for converting HTML strings into []telegraph.Node
  • Support go module
  • Add tests
  • Add benchmarks

Documentation

Overview

Package telegraph is a client for the Telegraph API.

https://telegra.ph/api

Index

Constants

View Source
const DefaultBaseURL = "https://api.telegra.ph"

DefaultBaseURL is the Telegraph API endpoint.

Variables

View Source
var ErrInvalidParameter = errors.New("telegraph: invalid parameter")

ErrInvalidParameter is wrapped by errors for parameters rejected before any request is sent.

Functions

func NodesToHTML added in v0.2.0

func NodesToHTML(nodes Nodes) (string, error)

NodesToHTML renders nodes, e.g. Page.Content, as an HTML fragment. Text and attribute values are escaped; attributes are written in key order.

Only the tags and attributes Telegraph accepts are rendered; any other is an error, because html.Render writes tag and attribute names verbatim. URLs in href and src are written as given: check their scheme (e.g. javascript:) before showing nodes from an untrusted source.

func Ptr added in v0.2.0

func Ptr[T any](v T) *T

Ptr returns a pointer to v, for optional parameters such as EditAccountInfoParams.AuthorName or GetViewsParams.Hour.

Types

type APIError added in v0.2.0

type APIError struct {
	Method string // API method, e.g. "createPage"
	Code   string // error from the API, e.g. "PAGE_NOT_FOUND"
}

APIError is returned when the API answers with "ok": false.

func (*APIError) Error added in v0.2.0

func (e *APIError) Error() string

func (*APIError) FloodWait added in v0.2.0

func (e *APIError) FloodWait() (time.Duration, bool)

FloodWait reports how long to wait before retrying when the API answered FLOOD_WAIT_<seconds>.

type Account

type Account struct {
	ShortName  string `json:"short_name"`
	AuthorName string `json:"author_name"`
	AuthorURL  string `json:"author_url"`

	// AccessToken is only returned by createAccount and revokeAccessToken.
	AccessToken string `json:"access_token,omitempty"`
	// AuthURL is valid for one use and for 5 minutes only.
	AuthURL   string `json:"auth_url,omitempty"`
	PageCount int    `json:"page_count,omitempty"`
}

Account represents a Telegraph account.

https://telegra.ph/api#Account

type AccountField added in v0.2.0

type AccountField string

AccountField names a field that GetAccountInfo can return.

const (
	FieldShortName  AccountField = "short_name"
	FieldAuthorName AccountField = "author_name"
	FieldAuthorURL  AccountField = "author_url"
	FieldAuthURL    AccountField = "auth_url"
	FieldPageCount  AccountField = "page_count"
)

Fields accepted by GetAccountInfo.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client calls the Telegraph API. It is safe for concurrent use. Get one from NewClient, Create or Load; the zero value is not usable.

func Create

func Create(ctx context.Context, params CreateAccountParams, opts ...Option) (*Client, error)

Create creates a new Telegraph account and returns a client for it.

func Load

func Load(ctx context.Context, accessToken string, opts ...Option) (*Client, error)

Load returns a client for an existing access token after checking it with GetAccountInfo.

func NewClient added in v0.2.0

func NewClient(accessToken string, opts ...Option) *Client

NewClient returns a client for accessToken without contacting the API. accessToken may be empty for methods that do not need one (CreateAccount, GetPage, GetViews).

func (*Client) AccessToken

func (c *Client) AccessToken() string

AccessToken returns the client's current access token. It changes after a successful RevokeAccessToken.

func (*Client) CreateAccount

func (c *Client) CreateAccount(ctx context.Context, p CreateAccountParams) (Account, error)

CreateAccount creates a new Telegraph account. The returned Account carries its access token. It does not change the client's own token; use Create for a client bound to the new account.

https://telegra.ph/api#createAccount

func (*Client) CreatePage

func (c *Client) CreatePage(ctx context.Context, p CreatePageParams) (Page, error)

CreatePage creates a new Telegraph page.

https://telegra.ph/api#createPage

func (*Client) CreatePageWithHTML

func (c *Client) CreatePageWithHTML(ctx context.Context, p CreatePageParams, htmlContent string) (Page, error)

CreatePageWithHTML creates a new page whose content is converted from htmlContent with NewNodesWithHTML. Any p.Content is replaced.

func (*Client) EditAccountInfo

func (c *Client) EditAccountInfo(ctx context.Context, p EditAccountInfoParams) (Account, error)

EditAccountInfo updates the account's information.

https://telegra.ph/api#editAccountInfo

func (*Client) EditPage

func (c *Client) EditPage(ctx context.Context, p EditPageParams) (Page, error)

EditPage edits an existing Telegraph page.

https://telegra.ph/api#editPage

func (*Client) EditPageWithHTML added in v0.2.0

func (c *Client) EditPageWithHTML(ctx context.Context, p EditPageParams, htmlContent string) (Page, error)

EditPageWithHTML edits an existing page with content converted from htmlContent with NewNodesWithHTML. Any p.Content is replaced.

func (*Client) GetAccountInfo

func (c *Client) GetAccountInfo(ctx context.Context, fields ...AccountField) (Account, error)

GetAccountInfo fetches the account's information. Without fields the API returns short_name, author_name and author_url.

https://telegra.ph/api#getAccountInfo

func (*Client) GetPage

func (c *Client) GetPage(ctx context.Context, path string, returnContent bool) (Page, error)

GetPage fetches a Telegraph page by its path (e.g. "Sample-Page-12-15"). No access token is sent: the API ignores it here and never returns Page.CanEdit (checked against the live API); CreatePage, EditPage and GetPageList do return it.

https://telegra.ph/api#getPage

func (*Client) GetPageList

func (c *Client) GetPageList(ctx context.Context, offset, limit int) (PageList, error)

GetPageList fetches pages of the account, most recently created first. offset is the sequential number of the first page; limit is 1-200, or 0 for the API's default of 50.

https://telegra.ph/api#getPageList

func (*Client) GetViews

func (c *Client) GetViews(ctx context.Context, path string, p GetViewsParams) (PageViews, error)

GetViews fetches the number of views for a Telegraph page.

https://telegra.ph/api#getViews

func (*Client) RevokeAccessToken

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

RevokeAccessToken revokes the access token and generates a new one, which the client uses from then on. The returned Account carries the new access_token and auth_url.

https://telegra.ph/api#revokeAccessToken

type CreateAccountParams added in v0.2.0

type CreateAccountParams struct {
	ShortName  string // required, 1-32 characters
	AuthorName string // optional, 0-128 characters
	AuthorURL  string // optional, 0-512 characters
}

CreateAccountParams are the parameters of CreateAccount.

type CreatePageParams added in v0.2.0

type CreatePageParams struct {
	Title         string // required, 1-256 characters
	AuthorName    string // optional, 0-128 characters
	AuthorURL     string // optional, 0-512 characters
	Content       Nodes  // required, up to 64 KB
	ReturnContent bool   // return Content in the resulting Page
}

CreatePageParams are the parameters of CreatePage.

type EditAccountInfoParams added in v0.2.0

type EditAccountInfoParams struct {
	ShortName  *string // 1-32 characters
	AuthorName *string // 0-128 characters
	AuthorURL  *string // 0-512 characters
}

EditAccountInfoParams are the parameters of EditAccountInfo. Only non-nil fields are sent; use Ptr("") to clear AuthorName or AuthorURL.

type EditPageParams added in v0.2.0

type EditPageParams struct {
	Path          string // required, path to the page
	Title         string // required, 1-256 characters
	AuthorName    string // optional, 0-128 characters
	AuthorURL     string // optional, 0-512 characters
	Content       Nodes  // required, up to 64 KB
	ReturnContent bool   // return Content in the resulting Page
}

EditPageParams are the parameters of EditPage.

type GetViewsParams added in v0.2.0

type GetViewsParams struct {
	Year  int  // 2000-2100, 0 = not set
	Month int  // 1-12, 0 = not set
	Day   int  // 1-31, 0 = not set
	Hour  *int // 0-24, nil = not set (0 is a valid hour, hence the pointer)
}

GetViewsParams narrows GetViews to a period. The zero value asks for total views. Each finer unit requires the coarser one: Month needs Year, Day needs Month, Hour needs Day.

type HTTPError added in v0.2.0

type HTTPError struct {
	Method     string
	StatusCode int
	Body       string // truncated to maxErrorBodyBytes
}

HTTPError is returned when the API answers with a non-2xx status and no API error in the body.

func (*HTTPError) Error added in v0.2.0

func (e *HTTPError) Error() string

type Node

type Node any

Node is a DOM node: a string (text node) or a NodeElement. A *NodeElement is also accepted when sending content.

https://telegra.ph/api#Node

func NewNodeWithElement

func NewNodeWithElement(tag string, attrs map[string]string, children []Node) Node

NewNodeWithElement creates an element node.

func NewNodeWithString

func NewNodeWithString(str string) Node

NewNodeWithString creates a text node.

type NodeElement

type NodeElement struct {
	Tag      string            `json:"tag"`
	Attrs    map[string]string `json:"attrs,omitempty"`
	Children Nodes             `json:"children,omitempty"`
}

NodeElement represents a DOM element node.

https://telegra.ph/api#NodeElement

type Nodes added in v0.2.0

type Nodes []Node

Nodes is a list of Node.

Decoding turns text nodes into string and element nodes into NodeElement, so content fetched from the API can be type-switched and sent back as is. Encoding fails on any value that is not a string, NodeElement or *NodeElement.

func NewNodesWithHTML

func NewNodesWithHTML(htmlContent string) (Nodes, error)

NewNodesWithHTML converts an HTML fragment into nodes the API accepts.

  • Supported tags are kept, with only href and src attributes.
  • h1/h2 become h3, h5/h6 become h4, del/strike become s.
  • script, style, noscript, template and SVG/MathML elements are removed with their content.
  • Other unsupported tags (div, span, font, ...) are unwrapped: their children are kept.

Text, whitespace included, is passed through unchanged.

func (Nodes) MarshalJSON added in v0.2.0

func (ns Nodes) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Nodes) UnmarshalJSON added in v0.2.0

func (ns *Nodes) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Option added in v0.2.0

type Option func(*Client)

Option configures a Client.

func WithBaseURL added in v0.2.0

func WithBaseURL(baseURL string) Option

WithBaseURL replaces DefaultBaseURL, e.g. with an httptest server.

func WithHTTPClient added in v0.2.0

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient makes the client send requests through hc.

func WithLogger added in v0.2.0

func WithLogger(l *slog.Logger) Option

WithLogger makes the client log each request at debug level. The access token is redacted from logged parameters.

type Page

type Page struct {
	Path        string `json:"path"`
	URL         string `json:"url"`
	Title       string `json:"title"`
	Description string `json:"description"`
	AuthorName  string `json:"author_name,omitempty"`
	AuthorURL   string `json:"author_url,omitempty"`
	ImageURL    string `json:"image_url,omitempty"`
	Content     Nodes  `json:"content,omitempty"`
	Views       int    `json:"views"`
	// CanEdit is only returned by createPage, editPage and getPageList, not by getPage.
	CanEdit bool `json:"can_edit,omitempty"`
}

Page represents a page on Telegraph.

https://telegra.ph/api#Page

type PageList

type PageList struct {
	TotalCount int    `json:"total_count"`
	Pages      []Page `json:"pages"`
}

PageList represents a list of pages belonging to an account, most recently created first.

https://telegra.ph/api#PageList

type PageViews

type PageViews struct {
	Views int `json:"views"`
}

PageViews represents the number of page views for a page.

https://telegra.ph/api#PageViews

Directories

Path Synopsis
samples
simple command

Jump to

Keyboard shortcuts

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