medium

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2017 License: MIT Imports: 12 Imported by: 0

README

go-medium

GitHub release Go Documentation MIT License CircleCI

go-medium is a Medium API client for Go.

As you know, Medium provides an official API client for Go, literally named medium-sdk-go. However, that client is not able to publish an article to the authorized user's publications. I decided to implement alternative Go client for Medium.

Installation

$ go install github.com/moutend/go-medium

Usage

First off, you need initialize a client like this:

c := medium.NewClient(clientID, clientSecret, accessToken)

It's not recommended but if you want to use self-issued token, set clientID and clientSecret blank.

go-medium doesn't provide a method for generating API token with client ID and client secret. However, it provides Token method which generates a new API token based off shortlive code and redirect URI. One way to generate API token with OAuth is launching the local web server and redirect HTTP request to that web server.

In the following example, it demonstrates the steps below:

  • Initialize a client with self-issued token.
  • Get information about current authorized user.
  • Get publications owned by current authorized user.
  • Create an article as Markdown format.
  • Post the article to the publication.
package main

import (
	"fmt"
	"log"

	medium "github.com/moutend/go-medium"
)

func main() {
	// It's not recommended, but it uses self-issued token in this example.
	accessToken := "self-issued-access-token"
	c := medium.NewClient("", "", accessToken)

	// Get information about current authorized user.
	// See user.go to check all exported fields.
	u, err := c.User()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("You are logged in as %s.", u.Username)

	// Get list of publications.
	ps, err := u.Publications()
	if err != nil {
		log.Fatal(err)
	}
	// It assumes that the user has one or more publications.
	// See publication.go to check all exported fields.
	if len(ps) == 0 {
		log.Fatalf("%s has no publications yet.\n", u.Username)
	}
	fmt.Printf("You have a publication named %s.\n", ps[0].Name)

	// Publish an article as Markdown format.
	// For more dail, see next section.
	article := medium.Article{
		Title:         "test",
		ContentFormat: "markdown",
		Content: `# Test

## Sub title

# Using Medium API

This article was published from command line.`,
	}
	// Publish an article to the first publication.
	// See article.go to check all exported fields of PostedArticle.
	pa, err := ps[0].Post(article)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Published an article at %s\n", a.URL)
}

Specifying PublishedAt

The default value of medium.Article.PublishedAt is current time, you don't have to specify when the article was published at. However, if you want to specify it, the timestamp must be formatted according to the layout below:

2006-01-02T15:04:05+07000

Valid range of published date

Note that you cannot specify the timestamp after current UTC+07:00. I don't know why but it will be treated as future post and Medium API will reject that post. For example, Japan standard Time is UTC+09:00, the article posted from machine which timezone is set as JST will be rejected.

Also, you cannot specify the date and time before Jan 1st, 1970.

LICENSE

MIT

Documentation

Overview

Package medium provides thin wrapper for Medium API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Article

type Article struct {
	Title           string   `json:"title"`
	ContentFormat   string   `json:"contentFormat"`
	Content         string   `json:"content"`
	CanonicalURL    string   `json:"canonicalUrl"`
	Tags            []string `json:"tags"`
	PublishStatus   string   `json:"publishStatus"`
	PublishedAt     string   `json:"publishedAt"`
	License         string   `json:"license"`
	NotifyFollowers bool     `json:"notifyFollowers"`
}

Article represents an article.

type Client

type Client struct {
	Root              *url.URL
	ApplicationID     string
	ApplicationSecret string
	AccessToken       string
	// contains filtered or unexported fields
}

Client represents Medium API client.

func NewClient

func NewClient(clientID, clientSecret, accessToken string) (c *Client)

NewClient returns API client.

func (*Client) Image

func (c *Client) Image(filename string) (i *Image, err error)

Image upload an image.

func (*Client) RefreshToken added in v0.3.0

func (c *Client) RefreshToken(refreshToken string) (token *Token, err error)

RefreshToken gets a new API token based off refresh token.

func (*Client) SetLogger

func (c *Client) SetLogger(logger *log.Logger)

SetLogger sets logger.

func (*Client) Token

func (c *Client) Token(code, redirectURI string) (token *Token, err error)

Token gets a new API token based off shortlive code and redirect URI.

func (*Client) User

func (c *Client) User() (u *User, err error)

User returns the authenticated user's details.

type Contributor

type Contributor struct {
	PublicationID string `json:"publicationId"`
	UserID        string `json:"userId"`
	Role          string `json:"role"`
}

Contributor represents a contributor for the specific publication.

type Error

type Error struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

Error represents medium API.

type Image

type Image struct {
	URL string `json:"url"`
	MD5 string `json:"md5"`
}

type PostedArticle

type PostedArticle struct {
	ID            string   `json:"id"`
	Title         string   `json:"title"`
	AuthorID      string   `json:"authorId"`
	Tags          []string `json:"tags"`
	URL           string   `json:"url"`
	CanonicalURL  string   `json:"canonicalUrl"`
	PublishStatus string   `json:"publishStatus"`
	PublishAt     int      `json:"publishedAt"`
	License       string   `json:"license"`
	LicenseURL    string   `json:"licenseUrl"`
}

PostedArticle represents an article on

type Publication

type Publication struct {
	ID          string `json:"id"`
	Description string `json:"description"`
	Name        string `json:"name"`
	URL         string `json:"url"`
	ImageURL    string `json:"imageUrl"`
	// contains filtered or unexported fields
}

Publication represents a Medium Publication.

func (*Publication) Contributors

func (p *Publication) Contributors() ([]*Contributor, error)

Contributors returns a list of contributors for the publication.

func (*Publication) Post

func (p *Publication) Post(a Article) (*PostedArticle, error)

Post posts an article to the authenticated user's publication.

type Token

type Token struct {
	TokenType    string   `json:"token_type"`
	AccessToken  string   `json:"access_token"`
	RefreshToken string   `json:"refresh_token"`
	Scope        []string `json:"scope"`
	ExpiresAt    int      `json:"expires_at"`
}

Token represents response from /v1/tokens.

type User

type User struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Name     string `json:"name"`
	URL      string `json:"url"`
	ImageURL string `json:"imageUrl"`
	// contains filtered or unexported fields
}

User represents a Medium user

func (*User) Post

func (u *User) Post(a Article) (*PostedArticle, error)

Post posts an article to the authenticated user's profile.

func (*User) Publications

func (u *User) Publications() (p []*Publication, err error)

Publications returns specified user's publications.

Jump to

Keyboard shortcuts

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