Categorygithub.com/ka2n/go-wordpress
modulepackage
0.0.0-20180206201500-3b8369ffcef3
Repository: https://github.com/ka2n/go-wordpress.git
Documentation: pkg.go.dev

# README

go-wordpress

GoDoc

A Go client library for the Wordpress REST API

Installation

go get github.com/robbiet480/go-wordpress

Usage

Quick example

package main

import (
  "context"
  "fmt"
  "net/http"

  "github.com/robbiet480/go-wordpress"
)

func main() {

  tp := wordpress.BasicAuthTransport{
    Username: USER,
    Password: PASSWORD,
  }

  // create wp-api client
  client, _ := wordpress.NewClient(API_BASE_URL, tp.Client())

  ctx := context.Background()

  // for eg, to get current user (GET /users/me)
  currentUser, resp, _ := client.Users.Me(ctx, nil)
  if resp != nil && resp.StatusCode != http.StatusOK {
    // handle error
  }

  // Or you can use your own structs (for custom endpoints, for example)
  // Below is the equivalent of `client.Posts.Get(ctx, 100, nil)`
  var obj MyCustomPostStruct
  resp, err := client.Get(ctx, "/posts/100", nil, &obj)
  // ...

  fmt.Printf("Current user %+v", currentUser)
}

For more examples, see package tests.

For list of supported/implemented endpoints, see Endpoints.md

Authentication

The go-wordpress library does not directly handle authentication. Instead, when creating a new client, pass an http.Client that can handle authentication for you.

Note that when using an authenticated Client, all calls made by the client will include the specified authentication transport token. Therefore, authenticated clients should almost never be shared between different users.

Username/Password or Application Password

A basic authentication (username/password) client for use with the WP-API BasicAuth plugin or Application Passwords plugin is included with the library. An example implementation can be found in example/basicauth/main.go.

OAuth 1.0a

If you use the OAuth 1.0a Server for authentication, you can find an example implementation in example/oauth2/main.go using the oauth1 library (which is very similar to the official OAuth 2.0 library). See the oauth1 docs for complete instructions on using that library.

OAuth 2.0 and JWT

If you are using the JWT plug-in for authentication, you can use the oauth2 library's StaticTokenSource. An example implementation can be found in example/oauth2/main.go. See the oauth2 docs for complete instructions on using that library.

Other authentication styles

For any other authentication methods, you should only need to provide a custom http.Client when creating a new WordPress client.

Pagination

All requests for resource collections (posts, pages, media, revisions, etc.) support pagination. Pagination options are described in the wordpress.ListOptions struct and passed to the list methods directly or as an embedded type of a more specific list options struct (for example wordpress.PostListOptions). Pages information is available via the wordpress.Response struct.

package main

import (
  "context"

  "github.com/robbiet480/go-wordpress"
)

func main() {
  tp := wordpress.BasicAuthTransport{
    Username: USER,
    Password: PASSWORD,
  }

  // create wp-api client
  client, _ := wordpress.NewClient(API_BASE_URL, tp.Client())

  ctx := context.Background()

  opt := &wordpress.PostListOptions{
    ListOptions: wordpress.ListOptions{PerPage: 10},
  }
  // get all pages of results
  var allPosts []*wordpress.Post
  for {
    posts, resp, err := client.Posts.List(ctx, opt)
    if err != nil {
      return err
    }
    allPosts = append(allPosts, posts...)
    if resp.NextPage == 0 {
      break
    }
    opt.Page = resp.NextPage
  }
}

Test

Note: Before running the tests, ensure that you have set up your test environment

Prerequisites

Setting up test environment

  • Install prequisites (see above)
  • Import ./test-data/go-wordpress.wordpress.2015-08-23.xml to your local test Wordpress installation
  • Upload at least one media to your Wordpress installation (Admin > Media > Upload)
  • Edit one (1) most recent Post to create a revision
  • Edit one (1) most recent Page to create a revision

Running tests

# Set test enviroment
export WP_API_URL=http://192.168.99.100:32777/wp-json/
export WP_USER=<user>
export WP_PASSWD=<password>

cd $GOPATH/src/github.com/robbiet480/go-wordpress
go test

Thanks

Large parts of this library were inspired if not outright copied from Google's excellent go-github library.

# Packages

No description provided by the author

# Functions

DiscoverAPI will discover the API root URL for the given base URL.
NewClient returns an initalized Client for the given baseURL and httpClient.

# Constants

Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
Constants for different post values.
TimeLayout is the layout string for a timestamp without timezone information like 2017-12-25T09:54:42.
TimeWithZoneLayout is the layout string for a timestamp with timezone information like 2017-09-24T13:28:06+00:00.

# Variables

DefaultHTTPClient is an http.Client with the DefaultHTTPTransport and (Cookie) Jar set nil.
DefaultHTTPTransport is an http.RoundTripper that has DisableKeepAlives set true.
ErrURLContainsWPV2 is returned from NewClient if URL contains /wp/v2.
Location is the time.Location used when decoding timestamps from WordPress.

# Structs

AvatarURLS returns different sizes of the users avatar.
BasicAuthTransport is an http.RoundTripper that authenticates all requests using HTTP Basic Authentication with the provided username and password.
Category represents a WordPress post/page category.
CategoryListOptions are options that can be passed to List().
Client is a struct containing values and methods used for interacting with the WordPress API.
Comment represents a WordPress post comment.
CommentListOptions are options that can be passed to List().
DeleteResponse is used when deleting an object.
DiscoveredAPI is a struct containing details about a discovered WordPress REST API.
Error is a generic WordPress error container.
ListOptions specifies the optional parameters to various List methods that support pagination.
Media represents a WordPress post media.
MediaDetails describes specific details about media.
MediaDetailsSizes provides different sizes of the same media item.
MediaDetailsSizesItem provides details for a single media item's size.
MediaListOptions are options that can be passed to List().
MediaUploadOptions are options that can be passed to Create().
Page represents a WordPress page.
PageListOptions are options that can be passed to List().
Post
Post represents a WordPress post.
PostListOptions are options that can be passed to List().
PostsTerm represents a WordPress post post term.
PostsTermsService provides access to the post term related functions in the WordPress REST API.
PostsTermsTaxonomyService contains data about the post terms taxonomy service.
RenderedString contains a raw and rendered version of a string such as title, content, excerpt, etc.
Response is a WordPress REST API response.
Revision represents a WordPress page/post revision.
RevisionsService provides access to the revision related functions in the WordPress REST API.
RootInfo is a struct containing basic and publicly available information about the WordPress REST API.
Settings represents a WordPress settings.
Status represents a WordPress post status.
Statuses describes multiple Statuses.
Tag represents a WordPress page/post tag.
TagListOptions are options that can be passed to List().
Taxonomy represents a WordPress taxonomy.
Term represents a WordPress page/post term.
TermsTaxonomyService contains information about a taxonomy term.
Time is a wrapper around time.Time with custom JSON marshal/unmarshal functions for the WordPress specific timestamp formats.
Type represents a WordPress item type.
TypeLabels represents a label that applies to a WordPress Type.
Types represents the assigned types for each item type.
User represents a WordPress user.
UserListOptions are options that can be passed to List().

# Type aliases

CategoriesService provides access to the category related functions in the WordPress REST API.
CommentsService provides access to the comment related functions in the WordPress REST API.
MediaService provides access to the media related functions in the WordPress REST API.
PagesService provides access to the page related functions in the WordPress REST API.
PostsService provides access to the post related functions in the WordPress REST API.
SettingsService provides access to the settings related functions in the WordPress REST API.
StatusesService provides access to the Status related functions in the WordPress REST API.
TagsService provides access to the Tag related functions in the WordPress REST API.
TaxonomiesService provides access to the Taxonomies related functions in the WordPress REST API.
TermsService provides access to the Terms related functions in the WordPress REST API.
TypesService provides access to the Type related functions in the WordPress REST API.
UsersService provides access to the Users related functions in the WordPress REST API.