Hey there, fellow developer! Ready to dive into the world of WordPress API integration using Go? Let's get cracking!
WordPress powers a huge chunk of the web, and its REST API opens up a world of possibilities. But why Go, you ask? Well, it's fast, concurrent, and just plain fun to work with. Plus, it's a great fit for building robust integrations. So, let's roll up our sleeves and get to work!
Before we jump in, make sure you've got:
Got all that? Great! Let's move on.
First things first, let's set up our project:
mkdir wp-api-integration cd wp-api-integration go mod init github.com/yourusername/wp-api-integration
Now, let's grab the packages we'll need:
go get github.com/go-resty/resty/v2 go get github.com/dgrijalva/jwt-go
WordPress API uses JWT for authentication. Let's set that up:
import ( "github.com/go-resty/resty/v2" "github.com/dgrijalva/jwt-go" ) type Client struct { BaseURL string Token string client *resty.Client } func NewClient(baseURL, username, password string) (*Client, error) { client := resty.New() resp, err := client.R(). SetBody(map[string]string{ "username": username, "password": password, }). Post(baseURL + "/jwt-auth/v1/token") if err != nil { return nil, err } var result map[string]interface{} if err := json.Unmarshal(resp.Body(), &result); err != nil { return nil, err } token := result["token"].(string) return &Client{ BaseURL: baseURL, Token: token, client: client, }, nil }
Now that we're authenticated, let's make some requests:
func (c *Client) GetPosts() ([]Post, error) { resp, err := c.client.R(). SetHeader("Authorization", "Bearer "+c.Token). Get(c.BaseURL + "/wp/v2/posts") if err != nil { return nil, err } var posts []Post if err := json.Unmarshal(resp.Body(), &posts); err != nil { return nil, err } return posts, nil } func (c *Client) CreatePost(title, content string) (*Post, error) { resp, err := c.client.R(). SetHeader("Authorization", "Bearer "+c.Token). SetBody(map[string]interface{}{ "title": title, "content": content, "status": "publish", }). Post(c.BaseURL + "/wp/v2/posts") if err != nil { return nil, err } var post Post if err := json.Unmarshal(resp.Body(), &post); err != nil { return nil, err } return &post, nil }
As you can see, we're using json.Unmarshal
to parse the JSON responses. Make sure to define your structs to match the API response:
type Post struct { ID int `json:"id"` Title struct { Rendered string `json:"rendered"` } `json:"title"` Content struct { Rendered string `json:"rendered"` } `json:"content"` // Add other fields as needed }
Let's put it all together:
func main() { client, err := NewClient("https://your-wordpress-site.com/wp-json", "username", "password") if err != nil { log.Fatal(err) } posts, err := client.GetPosts() if err != nil { log.Fatal(err) } fmt.Printf("Found %d posts\n", len(posts)) newPost, err := client.CreatePost("Hello, World!", "This is my first post via the API!") if err != nil { log.Fatal(err) } fmt.Printf("Created new post with ID: %d\n", newPost.ID) }
Always check for errors and log them appropriately. Consider using a logging package like logrus
for more advanced logging needs.
Don't forget to write tests! Here's a quick example:
func TestGetPosts(t *testing.T) { client, _ := NewClient("https://test-site.com/wp-json", "test", "test") posts, err := client.GetPosts() assert.NoError(t, err) assert.NotEmpty(t, posts) }
For better performance, consider using goroutines for concurrent requests and implement caching for frequently accessed data.
And there you have it! You've just built a WordPress API integration in Go. Pretty cool, right? Remember, this is just scratching the surface. The WordPress API has a ton of endpoints for you to explore, so keep experimenting and building awesome stuff!
Happy coding, and may your builds always be successful! 🚀