Hey there, fellow Go enthusiast! Ready to supercharge your application with some social proof? Let's dive into integrating the Trustpilot API into your Go project. Trustpilot is a powerhouse for collecting and showcasing customer reviews, and with this guide, you'll be pulling in those shiny stars in no time.
Before we jump in, make sure you've got:
Let's kick things off:
mkdir trustpilot-integration cd trustpilot-integration go mod init trustpilot-integration
Now, let's grab the packages we'll need:
go get github.com/go-resty/resty/v2 go get golang.org/x/oauth2
Alright, time to get cozy with OAuth 2.0. Here's a quick snippet to get your access token:
import ( "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" ) config := &clientcredentials.Config{ ClientID: "your-client-id", ClientSecret: "your-client-secret", TokenURL: "https://api-authentication.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken", } token, err := config.Token(context.Background()) if err != nil { // Handle error }
Now that we're authenticated, let's make some requests:
import "github.com/go-resty/resty/v2" client := resty.New() resp, err := client.R(). SetAuthToken(token.AccessToken). Get("https://api.trustpilot.com/v1/business-units/your-business-unit-id/reviews") if err != nil { // Handle error }
Time to parse that JSON:
type Review struct { ID string `json:"id"` Title string `json:"title"` Text string `json:"text"` // Add more fields as needed } var reviews []Review err = json.Unmarshal(resp.Body(), &reviews) if err != nil { // Handle error }
Let's fetch your company profile:
resp, err := client.R(). SetAuthToken(token.AccessToken). Get("https://api.trustpilot.com/v1/business-units/your-business-unit-id") // Parse the response similarly to the reviews
Don't be that person who hammers the API. Implement rate limiting:
import "golang.org/x/time/rate" limiter := rate.NewLimiter(rate.Every(time.Second), 5) // 5 requests per second if err := limiter.Wait(context.Background()); err != nil { // Handle error } // Make your API request here
Let's write a simple test:
func TestGetReviews(t *testing.T) { // Set up your test client and mock server reviews, err := GetReviews(testClient, "test-business-id") if err != nil { t.Fatalf("Expected no error, got %v", err) } if len(reviews) == 0 { t.Fatal("Expected reviews, got none") } }
And there you have it! You've just built a Trustpilot API integration in Go. Pretty cool, right? With this foundation, you can now fetch reviews, post invitation links, and even analyze your company's performance on Trustpilot.
Remember, the sky's the limit here. You could build a dashboard, automate review responses, or even create a fancy widget for your website. The Trustpilot world is your oyster!
Now go forth and integrate those reviews! Happy coding!