An open API service indexing awesome lists of open source software.

https://github.com/ableinc/go-notificationsapi

Unofficial Go NotificationsAPI SDK.
https://github.com/ableinc/go-notificationsapi

Last synced: 8 months ago
JSON representation

Unofficial Go NotificationsAPI SDK.

Awesome Lists containing this project

README

          

# NotificationAPI Go Server SDK

[![Go Version](https://img.shields.io/badge/go-%3E%3D1.24-blue.svg)](https://golang.org/)
[![License](https://img.shields.io/badge/license-ISC-green.svg)](https://opensource.org/licenses/ISC)

The official Go server SDK for [NotificationAPI](https://www.notificationapi.com). This library allows you to send notifications, manage users, and interact with the NotificationAPI platform from your Go applications.

## Features

- Send notifications across multiple channels (Email, SMS, Push, In-App, etc.)
- User management and identification
- Notification preferences management
- Scheduled notifications
- Sub-notifications
- Comprehensive logging and querying
- Regional API endpoint support
- Full type safety with Go structs

## Installation

```bash
go get github.com/ableinc/go-notificationsapi
```

## Quick Start

```go
package main

import (
"fmt"
"log"

"github.com/ableinc/go-notificationsapi"
)

func main() {
// Initialize the client
client, err := notificationapi.NewClient("your-client-id", "your-client-secret", nil)
if err != nil {
log.Fatal(err)
}

// Send a notification
req := notificationapi.SendRequest{
Type: stringPtr("welcome_email"),
To: &notificationapi.User{
ID: "user123",
Email: stringPtr("user@example.com"),
},
Parameters: map[string]interface{}{
"firstName": "John",
"lastName": "Doe",
},
}

resp, err := client.Send(req)
if err != nil {
log.Fatal(err)
}

fmt.Printf("Notification sent successfully: %d\n", resp.StatusCode)
}

// Helper function to create string pointers
func stringPtr(s string) *string {
return &s
}
```

## Configuration

### Regional Endpoints

You can configure the SDK to use different regional endpoints:

```go
// US Region (default)
client, err := notificationapi.NewClient(clientID, clientSecret, &notificationapi.InitConfiguration{
BaseURL: string(notificationapi.USRegion),
})

// EU Region
client, err := notificationapi.NewClient(clientID, clientSecret, &notificationapi.InitConfiguration{
BaseURL: string(notificationapi.EURegion),
})

// CA Region
client, err := notificationapi.NewClient(clientID, clientSecret, &notificationapi.InitConfiguration{
BaseURL: string(notificationapi.CARegion),
})

// Custom endpoint
client, err := notificationapi.NewClient(clientID, clientSecret, &notificationapi.InitConfiguration{
BaseURL: "https://your-custom-endpoint.com",
})
```

## Usage Examples

### Sending Notifications

#### Basic Notification

```go
req := notificationapi.SendRequest{
Type: stringPtr("user_welcome"),
To: &notificationapi.User{
ID: "user123",
Email: stringPtr("user@example.com"),
},
Parameters: map[string]interface{}{
"name": "John Doe",
"company": "Acme Corp",
},
}

resp, err := client.Send(req)
```

#### Notification with Channel-Specific Content

```go
req := notificationapi.SendRequest{
Type: stringPtr("order_confirmation"),
To: &notificationapi.User{
ID: "user123",
Email: stringPtr("user@example.com"),
Number: stringPtr("+1234567890"),
},
Email: &notificationapi.ChannelEmail{
Subject: "Order Confirmation #12345",
HTML: "

Thank you for your order!

Order #12345 has been confirmed.

",
},
SMS: &notificationapi.ChannelSMS{
Message: "Your order #12345 has been confirmed. Thank you!",
},
}

resp, err := client.Send(req)
```

#### Scheduled Notification

```go
req := notificationapi.SendRequest{
Type: stringPtr("reminder"),
To: &notificationapi.User{
ID: "user123",
Email: stringPtr("user@example.com"),
},
Schedule: stringPtr("2024-12-25T10:00:00Z"), // ISO 8601 format
Parameters: map[string]interface{}{
"eventName": "Holiday Sale",
},
}

resp, err := client.Send(req)
```

#### Force Specific Channels

```go
req := notificationapi.SendRequest{
Type: stringPtr("urgent_alert"),
To: &notificationapi.User{
ID: "user123",
Email: stringPtr("user@example.com"),
Number: stringPtr("+1234567890"),
},
ForceChannels: []notificationapi.Channels{
notificationapi.EMAIL,
notificationapi.SMS,
},
}

resp, err := client.Send(req)
```

### User Management

#### Identify User

```go
user := notificationapi.User{
ID: "user123",
Email: stringPtr("user@example.com"),
Number: stringPtr("+1234567890"),
Timezone: stringPtr("America/New_York"),
PushTokens: []notificationapi.PushToken{
{
Type: notificationapi.FCM,
Token: "fcm-token-here",
Device: notificationapi.Device{
DeviceID: "device123",
Platform: stringPtr("android"),
},
},
},
}

resp, err := client.IdentifyUser(user)
```

### User Preferences

#### Set User Preferences

```go
preferences := []notificationapi.SetUserPreferencesRequest{
{
NotificationID: "order_updates",
Channel: stringPtr(string(notificationapi.EMAIL)),
Delivery: stringPtr("daily"),
},
{
NotificationID: "marketing",
Delivery: stringPtr("off"),
},
}

resp, err := client.SetUserPreferences("user123", preferences)
```

#### Delete User Preferences

```go
// Delete all preferences for a notification
resp, err := client.DeleteUserPreferences("user123", "marketing", nil)

// Delete preferences for a specific sub-notification
subNotificationID := "special_offers"
resp, err := client.DeleteUserPreferences("user123", "marketing", &subNotificationID)
```

### Sub-Notifications

#### Create Sub-Notification

```go
req := notificationapi.CreateSubNotificationRequest{
NotificationID: "order_updates",
Title: "Express Shipping Updates",
SubNotificationID: "express_shipping",
}

resp, err := client.CreateSubNotification(req)
```

#### Delete Sub-Notification

```go
req := notificationapi.DeleteSubNotificationRequest{
NotificationID: "order_updates",
SubNotificationID: "express_shipping",
}

resp, err := client.DeleteSubNotification(req)
```

### In-App Notifications

#### Update In-App Notification Status

```go
req := notificationapi.InAppNotificationPatchRequest{
TrackingIDs: []string{"tracking-id-1", "tracking-id-2"},
Opened: stringPtr("2024-01-01T12:00:00Z"),
Clicked: stringPtr("2024-01-01T12:05:00Z"),
Reply: &notificationapi.ReplyInfo{
Date: "2024-01-01T12:10:00Z",
Message: "Thank you for the update!",
},
}

resp, err := client.UpdateInAppNotification("user123", req)
```

### Scheduled Notifications

#### Update Scheduled Notification

```go
updateReq := notificationapi.SendRequest{
Schedule: stringPtr("2024-12-26T10:00:00Z"), // New schedule
Parameters: map[string]interface{}{
"newParam": "updated value",
},
}

resp, err := client.UpdateSchedule("tracking-id", updateReq)
```

#### Delete Scheduled Notification

```go
resp, err := client.DeleteSchedule("tracking-id")
```

### Retract Notifications

```go
req := notificationapi.RetractRequest{
NotificationID: "order_confirmation",
UserID: "user123",
}

resp, err := client.Retract(req)
```

### Query Logs

#### Basic Log Query

```go
params := notificationapi.QueryLogsPostBody{
DateRangeFilter: &notificationapi.DateRangeFilter{
StartTime: int64Ptr(1640995200), // Unix timestamp
EndTime: int64Ptr(1641081600),
},
NotificationFilter: []string{"order_confirmation", "welcome_email"},
ChannelFilter: []notificationapi.Channels{notificationapi.EMAIL, notificationapi.SMS},
UserFilter: []string{"user123", "user456"},
StatusFilter: []string{"sent", "delivered"},
}

resp, err := client.QueryLogs(params)
```

#### Custom Log Query

```go
params := notificationapi.QueryLogsPostBody{
CustomFilter: stringPtr("fields @message | filter @logStream like /ERROR/ | sort @timestamp desc"),
}

resp, err := client.QueryLogs(params)
```

## Error Handling

The SDK automatically handles HTTP errors and provides detailed error messages:

```go
resp, err := client.Send(req)
if err != nil {
// Handle error
fmt.Printf("Error sending notification: %v\n", err)
return
}

// Check for warning responses (HTTP 202)
if resp.StatusCode == 202 {
// Warning logged automatically, but you can handle it here
fmt.Println("Notification sent with warnings")
}
```

## Email Options

### Email Attachments

```go
req := notificationapi.SendRequest{
Type: stringPtr("invoice"),
To: &notificationapi.User{
ID: "user123",
Email: stringPtr("user@example.com"),
},
Options: &notificationapi.NotificationOptions{
Email: &notificationapi.EmailOptions{
FromName: stringPtr("Acme Corp"),
FromAddress: stringPtr("noreply@acme.com"),
ReplyToAddresses: []string{"support@acme.com"},
CCAddresses: []string{"accounting@acme.com"},
Attachments: []notificationapi.EmailAttachment{
{
Filename: "invoice-12345.pdf",
URL: "https://secure.acme.com/invoices/12345.pdf",
},
},
},
},
}

resp, err := client.Send(req)
```

## Push Notifications

### Mobile Push Notifications

```go
// First, identify user with push tokens
user := notificationapi.User{
ID: "user123",
PushTokens: []notificationapi.PushToken{
{
Type: notificationapi.FCM,
Token: "fcm-device-token",
Device: notificationapi.Device{
DeviceID: "device123",
Platform: stringPtr("android"),
AppID: stringPtr("com.acme.app"),
},
},
{
Type: notificationapi.APN,
Token: "apn-device-token",
Device: notificationapi.Device{
DeviceID: "device456",
Platform: stringPtr("ios"),
AppID: stringPtr("com.acme.app"),
},
},
},
}

_, err := client.IdentifyUser(user)
if err != nil {
log.Fatal(err)
}

// Send push notification
req := notificationapi.SendRequest{
Type: stringPtr("new_message"),
To: &notificationapi.User{
ID: "user123",
},
MobilePush: &notificationapi.ChannelMobilePush{
Title: "New Message",
Message: "You have a new message from John",
},
Options: &notificationapi.NotificationOptions{
APN: &notificationapi.APNOptions{
Badge: intPtr(1),
Sound: stringPtr("default"),
ThreadID: stringPtr("messages"),
},
FCM: &notificationapi.FCMOptions{
Android: &notificationapi.AndroidFCMOptions{
Priority: stringPtr("high"),
TTL: intPtr(3600),
},
},
},
}

resp, err := client.Send(req)
```

### Web Push Notifications

```go
// First, identify user with web push tokens
user := notificationapi.User{
ID: "user123",
WebPushTokens: []notificationapi.WebPushToken{
{
Sub: notificationapi.PushSubscription{
Endpoint: "https://fcm.googleapis.com/fcm/send/...",
Keys: struct {
P256dh string `json:"p256dh"`
Auth string `json:"auth"`
}{
P256dh: "p256dh-key-here",
Auth: "auth-key-here",
},
},
},
},
}

_, err := client.IdentifyUser(user)
if err != nil {
log.Fatal(err)
}

// Send web push notification
req := notificationapi.SendRequest{
Type: stringPtr("breaking_news"),
To: &notificationapi.User{
ID: "user123",
},
WebPush: &notificationapi.ChannelWebPush{
Title: "Breaking News",
Message: "Important update from our team",
Icon: stringPtr("https://example.com/icon.png"),
URL: stringPtr("https://example.com/news/123"),
},
}

resp, err := client.Send(req)
```

## API Reference

### Types

#### Channels
- `EMAIL` - Email notifications
- `INAPP_WEB` - In-app web notifications
- `SMS` - SMS notifications
- `CALL` - Call notifications
- `PUSH` - Mobile push notifications
- `WEB_PUSH` - Web push notifications

#### Regions
- `USRegion` - United States (default)
- `EURegion` - European Union
- `CARegion` - Canada

#### Push Providers
- `FCM` - Firebase Cloud Messaging
- `APN` - Apple Push Notification service

### Helper Functions

Since Go doesn't have optional parameters, you'll often need to create pointers to basic types:

```go
// Helper functions you might want to add to your code
func stringPtr(s string) *string {
return &s
}

func intPtr(i int) *int {
return &i
}

func int64Ptr(i int64) *int64 {
return &i
}
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## Testing

Run the test suite:

```bash
go test -v
```

Run tests with coverage:

```bash
go test -v -cover
```

## License

This project is licensed under the ISC License - see the [LICENSE](LICENSE) file for details.

## Support

- [Documentation](https://docs.notificationapi.com)
- [API Reference](https://docs.notificationapi.com/reference)
- [Support Portal](https://notificationapi.com/support)
- [GitHub Issues](https://github.com/ableinc/go-notificationsapi/issues)

## Changelog

### v1.0.0
- Initial release
- Full feature parity with Node.js SDK
- Support for all NotificationAPI features
- Comprehensive test coverage
- Go 1.24+ support