Back

Step by Step Guide to Building a Travis CI API Integration in Go

Aug 7, 20247 minute read

Introduction

Hey there, fellow Go enthusiast! Ready to supercharge your CI/CD workflow with Travis CI? In this guide, we'll walk through building a Travis CI API integration using Go and the awesome go-travis package. Buckle up, because we're about to make your development process smoother than a freshly waxed surfboard.

Prerequisites

Before we dive in, make sure you've got:

  • Go installed (you're a Gopher, right?)
  • A Travis CI account (if not, go grab one – it's free for open-source projects!)
  • Some basic knowledge of Go and Travis CI (but don't worry, we'll keep it simple)

Setting up the project

Let's kick things off by creating a new Go project and installing the go-travis package:

mkdir travis-ci-integration && cd travis-ci-integration go mod init github.com/yourusername/travis-ci-integration go get github.com/shuheiktgw/go-travis

Authentication

First things first, we need to get cozy with Travis CI. Head over to your Travis CI account settings and grab your API token. Now, let's authenticate:

import ( "github.com/shuheiktgw/go-travis" ) client := travis.NewClient(travis.ApiOrgUrl, "your-travis-ci-api-token")

Basic API operations

Now that we're all set up, let's flex those API muscles:

Fetching repository information

repo, _, err := client.Repositories.Find("yourusername/your-repo") if err != nil { // Handle error } fmt.Printf("Repo ID: %d, Name: %s\n", repo.Id, repo.Name)

Listing builds

builds, _, err := client.Builds.List("yourusername/your-repo", nil) if err != nil { // Handle error } for _, build := range builds { fmt.Printf("Build ID: %d, State: %s\n", build.Id, build.State) }

Triggering a new build

request := &travis.BuildRequest{ Branch: "main", } build, _, err := client.Builds.Create("yourusername/your-repo", request) if err != nil { // Handle error } fmt.Printf("New build triggered: %d\n", build.Id)

Advanced usage

Ready to level up? Let's tackle some advanced operations:

Fetching job logs

log, _, err := client.Jobs.Log(jobId, true) if err != nil { // Handle error } fmt.Println(log.Content)

Cancelling builds

_, err := client.Builds.Cancel(buildId) if err != nil { // Handle error } fmt.Println("Build cancelled successfully")

Restarting builds

_, err := client.Builds.Restart(buildId) if err != nil { // Handle error } fmt.Println("Build restarted successfully")

Error handling and best practices

Remember, with great power comes great responsibility. Always handle your errors and respect API rate limits:

if err != nil { if rateLimitErr, ok := err.(*travis.RateLimitError); ok { fmt.Printf("Rate limit exceeded. Reset at %v\n", rateLimitErr.Reset) time.Sleep(time.Until(rateLimitErr.Reset)) // Retry the request } else { // Handle other errors } }

Testing the integration

Don't forget to test your integration! Here's a quick example using the httptest package:

func TestFetchRepository(t *testing.T) { // Set up test server server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte(`{"id": 1234, "name": "test-repo"}`)) })) defer server.Close() // Create client with test server URL client := travis.NewClient(server.URL, "test-token") // Test the function repo, _, err := client.Repositories.Find("test/repo") if err != nil { t.Fatalf("Unexpected error: %v", err) } if repo.Id != 1234 || repo.Name != "test-repo" { t.Errorf("Unexpected repository data") } }

Conclusion

And there you have it! You've just built a Travis CI API integration in Go. You're now armed with the power to automate your CI/CD workflow like a pro. Remember, this is just the tip of the iceberg – there's so much more you can do with the Travis CI API.

Keep exploring, keep building, and most importantly, keep having fun with Go!

Resources

Now go forth and conquer your CI/CD pipeline! 🚀