Back

Step by Step Guide to Building a OneSignal API Integration in Go

Aug 14, 20246 minute read

Introduction

Hey there, fellow Go enthusiast! Ready to supercharge your app with push notifications? Look no further than OneSignal's powerful API. In this guide, we'll walk through integrating OneSignal into your Go project using their official github.com/OneSignal/onesignal-go-api package. Buckle up, and let's dive in!

Prerequisites

Before we start coding, make sure you've got:

  • Go installed on your machine (you're a Gopher, right?)
  • A OneSignal account with an app set up
  • Your OneSignal API key and App ID handy

Got all that? Great! Let's move on to the fun part.

Setting up the project

First things first, let's create a new Go module:

mkdir onesignal-integration && cd onesignal-integration go mod init github.com/yourusername/onesignal-integration

Now, let's grab the OneSignal Go API package:

go get github.com/OneSignal/onesignal-go-api

Initializing the OneSignal client

Time to write some Go! Create a new file called main.go and let's set up our OneSignal client:

package main import ( "context" "fmt" "os" "github.com/OneSignal/onesignal-go-api" ) func main() { config := onesignal.NewConfiguration() client := onesignal.NewAPIClient(config) ctx := context.WithValue(context.Background(), onesignal.ContextAPIKey, onesignal.APIKey{ Key: os.Getenv("ONESIGNAL_API_KEY"), }) // We'll use this client and context for all our operations }

Pro tip: Keep your API key safe by using environment variables!

Implementing key functionalities

Sending a push notification

Let's send our first notification:

notification := *onesignal.NewNotification() notification.SetAppId(os.Getenv("ONESIGNAL_APP_ID")) notification.SetContents(map[string]interface{}{ "en": "Hello from Go!", }) notification.SetIncludedSegments([]string{"Subscribed Users"}) result, _, err := client.DefaultApi.CreateNotification(ctx).Notification(notification).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } fmt.Printf("Notification sent! ID: %s\n", result.Id)

Creating a notification template

Templates make life easier. Here's how to create one:

template := *onesignal.NewNotificationTemplate() template.SetName("Go Template") template.SetAppId(os.Getenv("ONESIGNAL_APP_ID")) template.SetContents(map[string]interface{}{ "en": "This is a template notification", }) result, _, err := client.DefaultApi.CreateTemplate(ctx).NotificationTemplate(template).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } fmt.Printf("Template created! ID: %s\n", result.Id)

Retrieving app information

Curious about your app's stats? Here's how to fetch them:

app, _, err := client.DefaultApi.GetApp(ctx, os.Getenv("ONESIGNAL_APP_ID")).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } fmt.Printf("App name: %s, Players: %d\n", app.Name, app.Players)

Managing devices/players

Let's add a new device to our app:

device := *onesignal.NewPlayer() device.SetAppId(os.Getenv("ONESIGNAL_APP_ID")) device.SetDeviceType(0) // 0 for iOS device.SetIdentifier("[email protected]") result, _, err := client.DefaultApi.CreatePlayer(ctx).Player(device).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } fmt.Printf("Device added! ID: %s\n", result.Id)

Error handling and best practices

Always check for errors after API calls. The OneSignal API has rate limits, so be mindful of how often you're making requests. Consider implementing exponential backoff for retries if you're doing bulk operations.

Testing the integration

Write unit tests for your integration, mocking the OneSignal client if necessary. Don't forget to manually test with real devices to ensure everything's working smoothly.

Conclusion

And there you have it! You've just built a solid OneSignal integration in Go. From sending notifications to managing devices, you're now equipped to keep your users engaged and informed.

Remember, this is just scratching the surface. The OneSignal API offers a ton more features, so don't be afraid to explore the official documentation for more advanced use cases.

Happy coding, and may your notifications always reach their targets! 🚀