Skip to content

About

The official GoLang SDK for Spyxpo Cloud Services

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Latest commit

 

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SCS SDK for Go

Official Go SDK for Spyxpo Cloud Services (SCS) - an open-source Backend-as-a-Service platform.

Installation

go get github.com/Spyxpo/golang_scs

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/Spyxpo/golang_scs"
)

func main() {
    ctx := context.Background()

    // Create a client with configuration
    client, err := scs.NewClient(&scs.Config{
        APIKey:    "your-api-key",
        ProjectID: "your-project-id",
        BaseURL:   "https://your-scs-instance.com",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Or load from scs-info.json file
    // client, err := scs.NewClientFromFile("scs-info.json")

    // Register a new user
    authResult, err := client.Auth().Register(ctx, scs.RegisterInput{
        Email:       "user@example.com",
        Password:    "password123",
        DisplayName: "John Doe",
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Registered user: %s\n", authResult.User.Email)
}

Configuration

Direct Configuration

client, err := scs.NewClient(&scs.Config{
    APIKey:    "pk_your_api_key",
    ProjectID: "your-project-id",
    BaseURL:   "https://your-scs-instance.com", // Optional, defaults to localhost:3001
})

From File (scs-info.json)

client, err := scs.NewClientFromFile("scs-info.json")

The scs-info.json file format:

{
  "sdk_config": {
    "api_key": "pk_your_api_key",
    "project_id": "your-project-id",
    "base_url": "https://your-scs-instance.com"
  }
}

Services

Authentication

// Register a new user
authResult, err := client.Auth().Register(ctx, scs.RegisterInput{
    Email:       "user@example.com",
    Password:    "password123",
    DisplayName: "John Doe",
})

// Login
authResult, err := client.Auth().Login(ctx, scs.LoginInput{
    Email:    "user@example.com",
    Password: "password123",
})

// Get current user
user, err := client.Auth().GetCurrentUser(ctx)

// Update profile
user, err := client.Auth().UpdateProfile(ctx, scs.UpdateProfileInput{
    DisplayName: "Jane Doe",
    PhotoURL:    "https://example.com/photo.jpg",
})

// Change password
err := client.Auth().ChangePassword(ctx, scs.ChangePasswordInput{
    CurrentPassword: "oldpassword",
    NewPassword:     "newpassword",
})

// Logout
client.Auth().Logout()

// Admin: List all users
users, err := client.Auth().ListUsers(ctx)

// Admin: Disable/Enable user
err := client.Auth().DisableUser(ctx, "user-uid")
err := client.Auth().EnableUser(ctx, "user-uid")

OAuth and Social Sign-In

SCS supports multiple OAuth providers for seamless social authentication. Each provider uses type-safe input structs for compile-time safety.

Google Sign-In

Authenticate users with their Google account.

// Sign in with Google
authResult, err := client.Auth().SignInWithGoogle(ctx, scs.GoogleSignInInput{
    IDToken:     "google-id-token",      // Required: ID token from Google Sign-In
    AccessToken: "google-access-token",   // Optional: Access token for additional scopes
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("User ID: %s\n", authResult.User.UID)
fmt.Printf("Email: %s\n", authResult.User.Email)
fmt.Printf("Display Name: %s\n", authResult.User.DisplayName)
fmt.Printf("Provider: %s\n", authResult.User.ProviderID)

GoogleSignInInput Fields:

Field Type Required Description
IDToken string Yes ID token from Google Sign-In SDK
AccessToken string No Access token for additional Google API scopes

Returns: *AuthResult containing token and user

Facebook Sign-In

Authenticate users with their Facebook account.

// Sign in with Facebook
authResult, err := client.Auth().SignInWithFacebook(ctx, scs.FacebookSignInInput{
    AccessToken: "facebook-access-token",  // Required
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Welcome, %s!\n", authResult.User.DisplayName)

FacebookSignInInput Fields:

Field Type Required Description
AccessToken string Yes Access token from Facebook Login SDK
Apple Sign-In

Authenticate users with their Apple ID. Required for iOS apps with social login.

// Sign in with Apple
authResult, err := client.Auth().SignInWithApple(ctx, scs.AppleSignInInput{
    IdentityToken:     "apple-identity-token",  // Required
    AuthorizationCode: "apple-auth-code",       // Optional
    FullName:          "John Doe",              // Optional, first sign-in only
})

AppleSignInInput Fields:

Field Type Required Description
IdentityToken string Yes JWT identity token from Sign in with Apple
AuthorizationCode string No Authorization code for additional verification
FullName string No User's full name (Apple only provides this on first sign-in)

Important Notes:

  • Apple only provides the user's name on the first sign-in. Store it immediately.
  • Users can choose to hide their email (Apple provides a relay email).
GitHub Sign-In

Authenticate users with their GitHub account. Popular for developer-focused apps.

// Sign in with GitHub
authResult, err := client.Auth().SignInWithGitHub(ctx, scs.GitHubSignInInput{
    Code:        "github-oauth-code",                   // Required
    RedirectURI: "https://yourapp.com/callback",        // Optional
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("GitHub user: %s\n", authResult.User.DisplayName)

GitHubSignInInput Fields:

Field Type Required Description
Code string Yes OAuth authorization code from GitHub OAuth flow
RedirectURI string No Redirect URI (must match GitHub OAuth App settings)

OAuth Flow Example (Gin):

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/Spyxpo/golang_scs"
)

func main() {
    r := gin.Default()
    client, _ := scs.NewClient(&scs.Config{...})

    // Step 1: Redirect to GitHub
    r.GET("/login/github", func(c *gin.Context) {
        authURL := "https://github.com/login/oauth/authorize" +
            "?client_id=YOUR_CLIENT_ID" +
            "&redirect_uri=https://yourapp.com/callback" +
            "&scope=read:user user:email"
        c.Redirect(302, authURL)
    })

    // Step 2: Handle callback
    r.GET("/callback", func(c *gin.Context) {
        code := c.Query("code")
        if code == "" {
            c.JSON(400, gin.H{"error": "No code provided"})
            return
        }

        authResult, err := client.Auth().SignInWithGitHub(c.Request.Context(), scs.GitHubSignInInput{
            Code:        code,
            RedirectURI: "https://yourapp.com/callback",
        })
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        c.JSON(200, gin.H{"user": authResult.User})
    })

    r.Run()
}
Twitter/X Sign-In

Authenticate users with their Twitter/X account using OAuth 1.0a.

// Sign in with Twitter/X
authResult, err := client.Auth().SignInWithTwitter(ctx, scs.TwitterSignInInput{
    OAuthToken:       "twitter-oauth-token",        // Required
    OAuthTokenSecret: "twitter-oauth-secret",       // Required
})

TwitterSignInInput Fields:

Field Type Required Description
OAuthToken string Yes OAuth token from Twitter authentication
OAuthTokenSecret string Yes OAuth token secret from Twitter authentication
Microsoft Sign-In

Authenticate users with their Microsoft account (personal, work, or school).

// Sign in with Microsoft
authResult, err := client.Auth().SignInWithMicrosoft(ctx, scs.MicrosoftSignInInput{
    AccessToken: "microsoft-access-token",   // Required
    IDToken:     "microsoft-id-token",       // Optional
})

MicrosoftSignInInput Fields:

Field Type Required Description
AccessToken string Yes Access token from MSAL
IDToken string No ID token for additional user claims

Anonymous Authentication

Allow users to use your app without creating an account. Anonymous accounts can be upgraded later.

// Sign in anonymously (creates a temporary account)
authResult, err := client.Auth().SignInAnonymously(ctx, scs.AnonymousSignInInput{
    CustomData: map[string]interface{}{
        "referrer": "landing-page",
        "campaign": "summer-sale",
    }, // optional
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Anonymous user ID: %s\n", authResult.User.UID)
fmt.Printf("Is anonymous: %v\n", authResult.User.IsAnonymous)

AnonymousSignInInput Fields:

Field Type Required Description
CustomData map[string]interface{} No Custom data for analytics

Use Cases:

  • Allow users to try your app before signing up
  • Guest checkout in e-commerce
  • Save user progress/preferences before account creation

Converting Anonymous to Permanent Account:

// User decides to create a permanent account
// Link their anonymous account to a provider
user, err := client.Auth().LinkProvider(ctx, "google", map[string]interface{}{
    "idToken": "google-id-token",
})
if err != nil {
    if strings.Contains(err.Error(), "credential-already-in-use") {
        log.Println("This Google account is already registered")
    } else {
        log.Fatal(err)
    }
}

fmt.Println("Account upgraded! User data preserved.")
fmt.Printf("Is anonymous: %v\n", user.IsAnonymous) // false

Phone Number Authentication

Two-step authentication flow using SMS verification codes.

// Step 1: Send verification code to phone
result, err := client.Auth().SendPhoneVerificationCode(ctx, scs.PhoneVerificationInput{
    PhoneNumber:    "+1234567890",        // Required: E.164 format
    RecaptchaToken: "recaptcha-token",    // Optional: For bot protection
})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Verification ID: %s\n", result.VerificationID)

// Step 2: Verify code and sign in
authResult, err := client.Auth().SignInWithPhoneNumber(ctx, scs.PhoneSignInInput{
    VerificationID: result.VerificationID,
    Code:           "123456",  // 6-digit code from SMS
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Phone verified: %s\n", authResult.User.PhoneNumber)

PhoneVerificationInput Fields:

Field Type Required Description
PhoneNumber string Yes Phone number in E.164 format (e.g., +1234567890)
RecaptchaToken string No reCAPTCHA token for abuse prevention

PhoneSignInInput Fields:

Field Type Required Description
VerificationID string Yes Verification ID from SendPhoneVerificationCode
Code string Yes 6-digit verification code from SMS

Complete Flow Example:

func signInWithPhone(ctx context.Context, client *scs.Client, phoneNumber string) (*scs.AuthResult, error) {
    // Step 1: Send code
    result, err := client.Auth().SendPhoneVerificationCode(ctx, scs.PhoneVerificationInput{
        PhoneNumber: phoneNumber,
    })
    if err != nil {
        switch {
        case strings.Contains(err.Error(), "invalid-phone-number"):
            return nil, fmt.Errorf("invalid phone number format, use E.164 format (+1234567890)")
        case strings.Contains(err.Error(), "too-many-requests"):
            return nil, fmt.Errorf("too many attempts, please try again later")
        default:
            return nil, err
        }
    }

    // Get code from user (your UI implementation)
    code := promptUserForCode()

    // Step 2: Verify code
    authResult, err := client.Auth().SignInWithPhoneNumber(ctx, scs.PhoneSignInInput{
        VerificationID: result.VerificationID,
        Code:           code,
    })
    if err != nil {
        switch {
        case strings.Contains(err.Error(), "invalid-verification-code"):
            return nil, fmt.Errorf("invalid verification code")
        case strings.Contains(err.Error(), "code-expired"):
            return nil, fmt.Errorf("code expired, please request a new one")
        default:
            return nil, err
        }
    }

    return authResult, nil
}

Custom Token Authentication

Sign in using a JWT token generated by your backend. Useful for migration or custom auth.

// Sign in with a custom token (generated by your backend)
authResult, err := client.Auth().SignInWithCustomToken(ctx, "your-custom-jwt-token")
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Signed in user: %s\n", authResult.User.UID)

Backend Token Generation Example:

import (
    "time"
    "github.com/golang-jwt/jwt/v5"
)

func createCustomToken(uid string, claims map[string]interface{}) (string, error) {
    now := time.Now()

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "uid":    uid,
        "claims": claims,
        "iat":    now.Unix(),
        "exp":    now.Add(time.Hour).Unix(),
    })

    return token.SignedString([]byte(os.Getenv("SCS_SECRET_KEY")))
}

// Generate token for a user
customToken, err := createCustomToken("user-123", map[string]interface{}{
    "role": "admin",
})
// Send this token to the client for sign-in

Use Cases:

  • Migrating users from another authentication system
  • Server-side user creation with immediate client sign-in
  • Integration with enterprise SSO systems
  • Machine-to-machine authentication

Account Linking

Link multiple authentication providers to a single account.

// Link a provider to current account
user, err := client.Auth().LinkProvider(ctx, "facebook", map[string]interface{}{
    "accessToken": "facebook-access-token",
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Linked providers: %v\n", user.ProviderData)

// Unlink a provider from current account
user, err = client.Auth().UnlinkProvider(ctx, "facebook")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Remaining providers: %v\n", user.ProviderData)

// Get available sign-in methods for an email
result, err := client.Auth().FetchSignInMethodsForEmail(ctx, "user@example.com")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Available methods: %v\n", result.Methods)
// ["password", "google", "facebook"]

Supported Providers and Credentials:

Provider Required Credentials
google {"idToken": "...", "accessToken": "..."}
facebook {"accessToken": "..."}
apple {"identityToken": "...", "authorizationCode": "...", "fullName": "..."}
github {"code": "...", "redirectUri": "..."}
twitter {"oauthToken": "...", "oauthTokenSecret": "..."}
microsoft {"accessToken": "...", "idToken": "..."}

Password Reset & Email Verification

Handle password recovery and email verification flows.

// Send password reset email
err := client.Auth().SendPasswordResetEmail(ctx, "user@example.com")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Password reset email sent")

// Confirm password reset (user clicks link, you extract the code)
err = client.Auth().ConfirmPasswordReset(ctx, scs.PasswordResetInput{
    Code:        "reset-code-from-email",
    NewPassword: "newSecurePassword123",
})
if err != nil {
    log.Fatal(err)
}
fmt.Println("Password successfully reset")

// Send email verification to current user
err = client.Auth().SendEmailVerification(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Verification email sent")

// Verify email with code (user clicks link, you extract the code)
err = client.Auth().VerifyEmail(ctx, "verification-code")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Email verified")

PasswordResetInput Fields:

Field Type Required Description
Code string Yes Reset code from the email link
NewPassword string Yes User's new password

Error Handling:

func resetPassword(ctx context.Context, client *scs.Client, email string) error {
    err := client.Auth().SendPasswordResetEmail(ctx, email)
    if err != nil {
        // Don't reveal if user exists for security
        if strings.Contains(err.Error(), "user-not-found") {
            // Still return success to prevent email enumeration
            return nil
        }
        if strings.Contains(err.Error(), "too-many-requests") {
            return fmt.Errorf("too many attempts, please try later")
        }
        return err
    }
    return nil
}

func confirmReset(ctx context.Context, client *scs.Client, code, newPassword string) error {
    if len(newPassword) < 8 {
        return fmt.Errorf("password must be at least 8 characters")
    }

    err := client.Auth().ConfirmPasswordReset(ctx, scs.PasswordResetInput{
        Code:        code,
        NewPassword: newPassword,
    })
    if err != nil {
        switch {
        case strings.Contains(err.Error(), "expired-action-code"):
            return fmt.Errorf("reset link expired, please request a new one")
        case strings.Contains(err.Error(), "invalid-action-code"):
            return fmt.Errorf("invalid reset link")
        case strings.Contains(err.Error(), "weak-password"):
            return fmt.Errorf("password is too weak")
        default:
            return err
        }
    }
    return nil
}

Complete Authentication Example

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/Spyxpo/golang_scs"
)

type AuthService struct {
    client *scs.Client
}

func NewAuthService(config *scs.Config) (*AuthService, error) {
    client, err := scs.NewClient(config)
    if err != nil {
        return nil, err
    }
    return &AuthService{client: client}, nil
}

func (s *AuthService) Register(ctx context.Context, email, password, displayName string) (*scs.User, error) {
    authResult, err := s.client.Auth().Register(ctx, scs.RegisterInput{
        Email:       email,
        Password:    password,
        DisplayName: displayName,
    })
    if err != nil {
        return nil, err
    }

    // Send verification email
    _ = s.client.Auth().SendEmailVerification(ctx)

    return authResult.User, nil
}

func (s *AuthService) Login(ctx context.Context, email, password string) (*scs.AuthResult, error) {
    return s.client.Auth().Login(ctx, scs.LoginInput{
        Email:    email,
        Password: password,
    })
}

func (s *AuthService) SocialLogin(ctx context.Context, provider string, credentials map[string]interface{}) (*scs.AuthResult, error) {
    switch provider {
    case "google":
        return s.client.Auth().SignInWithGoogle(ctx, scs.GoogleSignInInput{
            IDToken:     credentials["idToken"].(string),
            AccessToken: credentials["accessToken"].(string),
        })
    case "facebook":
        return s.client.Auth().SignInWithFacebook(ctx, scs.FacebookSignInInput{
            AccessToken: credentials["accessToken"].(string),
        })
    case "github":
        return s.client.Auth().SignInWithGitHub(ctx, scs.GitHubSignInInput{
            Code:        credentials["code"].(string),
            RedirectURI: credentials["redirectUri"].(string),
        })
    default:
        return nil, fmt.Errorf("unknown provider: %s", provider)
    }
}

func (s *AuthService) ContinueAsGuest(ctx context.Context, customData map[string]interface{}) (*scs.AuthResult, error) {
    return s.client.Auth().SignInAnonymously(ctx, scs.AnonymousSignInInput{
        CustomData: customData,
    })
}

func (s *AuthService) UpgradeGuestAccount(ctx context.Context, provider string, credentials map[string]interface{}) (*scs.User, error) {
    user, err := s.client.Auth().GetCurrentUser(ctx)
    if err != nil {
        return nil, err
    }
    if !user.IsAnonymous {
        return nil, fmt.Errorf("current user is not anonymous")
    }

    return s.client.Auth().LinkProvider(ctx, provider, credentials)
}

func (s *AuthService) Logout() {
    s.client.Auth().Logout()
}

func main() {
    ctx := context.Background()

    auth, err := NewAuthService(&scs.Config{
        APIKey:    "your-api-key",
        ProjectID: "your-project-id",
        BaseURL:   "https://your-scs-instance.com",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Register new user
    user, err := auth.Register(ctx, "user@example.com", "password123", "John Doe")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Registered: %s\n", user.Email)

    // Or sign in with Google
    googleResult, err := auth.SocialLogin(ctx, "google", map[string]interface{}{
        "idToken":     "xxx",
        "accessToken": "yyy",
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Google user: %s\n", googleResult.User.Email)

    // Or continue as guest and upgrade later
    guest, err := auth.ContinueAsGuest(ctx, map[string]interface{}{
        "source": "homepage",
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Guest ID: %s\n", guest.User.UID)
}

### Database

NoSQL document database with collections and subcollections. SCS supports two powerful database options:

#### Database Types

| Type | Name | Description | Best For |
|------|------|-------------|----------|
| `eazi` | **eaZI Database** | Document-based NoSQL with Firestore-like collections, documents, and subcollections | Development, prototyping, small to medium apps |
| `reladb` | **RelaDB** | Production-grade NoSQL database with relational-style views | Production, scalability, advanced queries |

#### Initialize with eaZI (Default)

```go
import "github.com/spyxpo/scs-sdk-go/scs"

// eaZI is the default database - no special configuration needed
client, err := scs.NewClient(&scs.Config{
    ProjectID: "your-project-id",
    APIKey:    "your-api-key",
    // DatabaseType: "eazi" is implicit
})

Initialize with RelaDB (Production)

import "github.com/spyxpo/scs-sdk-go/scs"

// Use RelaDB for production
client, err := scs.NewClient(&scs.Config{
    ProjectID:    "your-project-id",
    APIKey:       "your-api-key",
    DatabaseType: "reladb",  // Enable RelaDB
})

eaZI Database Features

  • Document-based: Firestore-like collections and documents
  • Subcollections: Nested data organization
  • File-based storage: No external dependencies required
  • Zero configuration: Works out of the box
  • Query support: Filtering, ordering, and pagination

RelaDB Features

  • Production-ready: Built for reliability and performance
  • Scalable: Horizontal scaling and replication support
  • Advanced queries: Aggregation pipelines, complex filters
  • Indexing: Custom indexes for optimized performance
  • Schema flexibility: Dynamic schema with validation support
  • Relational-style views: Table view with columns and rows in the console

Collection Operations

// Get a collection reference
users := client.Database().Collection("users")

// List all collections
collections, err := client.Database().ListCollections(ctx)

// Create a collection
collection, err := client.Database().CreateCollection(ctx, "newCollection")

// Delete a collection
err = client.Database().DeleteCollection(ctx, "oldCollection")

Document Operations

// Add document with auto-generated ID
doc, err := client.Database().Collection("users").Add(ctx, map[string]interface{}{
    "name":  "John Doe",
    "email": "john@example.com",
    "age":   30,
    "tags":  []string{"developer", "golang"},
    "profile": map[string]interface{}{
        "bio":    "Software developer",
        "avatar": "https://example.com/avatar.jpg",
    },
})
fmt.Printf("Document ID: %s\n", doc.ID)

// Set document with custom ID (creates or overwrites)
doc, err := client.Database().Collection("users").Doc("user-123").Set(ctx, map[string]interface{}{
    "name":  "Jane Doe",
    "email": "jane@example.com",
})

// Get a single document
user, err := client.Database().Collection("users").Doc("user-123").Get(ctx)
fmt.Println(user.Data)

// Update document (partial update)
doc, err := client.Database().Collection("users").Doc("user-123").Update(ctx, map[string]interface{}{
    "age": 31,
})

// Delete document
err = client.Database().Collection("users").Doc("user-123").Delete(ctx)

Query Operations

// Simple query with single filter
activeUsers, err := client.Database().Collection("users").
    Where("status", "==", "active").
    Get(ctx)

// Multiple filters
results, err := client.Database().Collection("users").
    Where("age", ">=", 18).
    Where("status", "==", "active").
    Get(ctx)

// Ordering and pagination
posts, err := client.Database().Collection("posts").
    Where("published", "==", true).
    OrderBy("createdAt", "desc").
    Limit(10).
    Skip(20).
    Get(ctx)

// Using 'in' operator
featured, err := client.Database().Collection("posts").
    Where("category", "in", []string{"tech", "science", "news"}).
    Get(ctx)

// Using 'contains' for array fields
tagged, err := client.Database().Collection("posts").
    Where("tags", "contains", "golang").
    Get(ctx)

Query Operators

Operator Description Example
== Equal to .Where("status", "==", "active")
!= Not equal to .Where("status", "!=", "deleted")
> Greater than .Where("age", ">", 18)
>= Greater than or equal .Where("age", ">=", 18)
< Less than .Where("price", "<", 100)
<= Less than or equal .Where("price", "<=", 50)
in Value in array .Where("status", "in", []string{"active", "pending"})
contains Array contains value .Where("tags", "contains", "featured")

Subcollections

// Access a subcollection
postsRef := client.Database().
    Collection("users").
    Doc("userId").
    Collection("posts")

// Add to subcollection
post, err := postsRef.Add(ctx, map[string]interface{}{
    "title":     "My First Post",
    "content":   "Hello World!",
    "createdAt": time.Now().Format(time.RFC3339),
})

// Query subcollection
userPosts, err := postsRef.
    OrderBy("createdAt", "desc").
    Limit(5).
    Get(ctx)

// Nested subcollections (e.g., users/userId/posts/postId/comments)
commentsRef := client.Database().
    Collection("users").
    Doc("userId").
    Collection("posts").
    Doc("postId").
    Collection("comments")

// List subcollections of a document
subcollections, err := client.Database().
    Collection("users").
    Doc("userId").
    ListCollections(ctx)

Storage

// Upload a file
file, err := client.Storage().Upload(ctx, "/path/to/file.jpg", &scs.UploadOptions{
    Folder: "images",
})
fmt.Printf("Uploaded: %s\n", file.URL)

// Upload from io.Reader
reader := bytes.NewReader(data)
file, err := client.Storage().UploadReader(ctx, reader, "document.pdf", &scs.UploadOptions{
    Folder: "documents",
})

// List files
files, err := client.Storage().ListFiles(ctx)

// List files in folder
files, err := client.Storage().ListFilesInFolder(ctx, "images")

// Get file info
file, err := client.Storage().GetFile(ctx, "file-id")

// Download file
reader, contentType, err := client.Storage().Download(ctx, "file-id")
defer reader.Close()

// Delete file
err := client.Storage().Delete(ctx, "file-id")

// Create folder
folder, err := client.Storage().CreateFolder(ctx, "documents/reports")

// Get URLs
downloadURL := client.Storage().GetDownloadURL("file-id")
viewURL := client.Storage().GetViewURL("file-id")

Messaging (Push Notifications)

// Register device token
err := client.Messaging().RegisterToken(ctx, "device-token", "ios")

// Send to topic
msg, err := client.Messaging().SendToTopic(ctx, "news", "Breaking News", "Something happened!", map[string]interface{}{
    "articleId": "123",
})

// Send to specific token
msg, err := client.Messaging().SendToToken(ctx, "device-token", "Hello", "You have a message", nil)

// Send to multiple tokens
msg, err := client.Messaging().Send(ctx, scs.SendMessageInput{
    Title:  "Update Available",
    Body:   "A new version is available",
    Tokens: []string{"token1", "token2", "token3"},
})

// Topic management
topic, err := client.Messaging().CreateTopic(ctx, "announcements")
err := client.Messaging().SubscribeToTopic(ctx, "device-token", "announcements")
err := client.Messaging().UnsubscribeFromTopic(ctx, "device-token", "announcements")

// List topics
topics, err := client.Messaging().ListTopics(ctx)

Remote Config

// Fetch configuration
config, err := client.RemoteConfig().Fetch(ctx)

// Get values with defaults
welcomeMsg := client.RemoteConfig().GetString("welcome_message", "Hello!")
maxItems := client.RemoteConfig().GetInt("max_items", 10)
featureEnabled := client.RemoteConfig().GetBool("new_feature_enabled", false)
ratio := client.RemoteConfig().GetFloat("conversion_ratio", 1.0)

// Get all config
allConfig := client.RemoteConfig().GetAll()

// Admin: Manage parameters
param, err := client.RemoteConfig().CreateParameter(ctx, scs.ConfigParameter{
    Key:         "welcome_message",
    Value:       "Welcome to our app!",
    Description: "Welcome message shown on home screen",
})

param, err := client.RemoteConfig().UpdateParameter(ctx, "welcome_message", "New welcome message!")
err := client.RemoteConfig().DeleteParameter(ctx, "welcome_message")

// Publish changes
version, err := client.RemoteConfig().Publish(ctx, "Updated welcome message")

// Rollback to previous version
err := client.RemoteConfig().Rollback(ctx, 2)

Cloud Functions

// Invoke a function
result, err := client.Functions().Invoke(ctx, "processImage", map[string]interface{}{
    "imageUrl": "https://example.com/image.jpg",
    "resize":   true,
})
fmt.Printf("Result: %v\n", result.Result)

// Admin: Create a function
fn, err := client.Functions().Create(ctx, scs.CreateFunctionInput{
    Name:        "processImage",
    Description: "Processes and resizes images",
    Runtime:     "nodejs18",
    Handler:     "index.handler",
    Code:        `exports.handler = async (event) => { return { processed: true }; }`,
    Timeout:     30,
    Memory:      256,
    Environment: map[string]string{
        "NODE_ENV": "production",
    },
})

// Admin: List functions
functions, err := client.Functions().List(ctx)

// Admin: Update a function
fn, err := client.Functions().Update(ctx, "function-id", scs.UpdateFunctionInput{
    Code: `exports.handler = async (event) => { return { v2: true }; }`,
})

// Admin: Delete a function
err := client.Functions().Delete(ctx, "function-id")

// Admin: Get logs
logs, err := client.Functions().GetLogs(ctx, "function-id")

Hosting

// Deploy a site
deployment, err := client.Hosting().Deploy(ctx, "./dist", "v1.0.0")
fmt.Printf("Deployed to: %s\n", deployment.URL)

// List deployments
deployments, err := client.Hosting().ListDeployments(ctx)

// Activate a specific deployment
deployment, err := client.Hosting().Activate(ctx, "deployment-id")

// Rollback to previous deployment
deployment, err := client.Hosting().Rollback(ctx, "previous-deployment-id")

// Custom domains
domain, err := client.Hosting().AddDomain(ctx, "example.com")
domain, err := client.Hosting().VerifyDomain(ctx, "domain-id")
err := client.Hosting().DeleteDomain(ctx, "domain-id")

AI Services

Chat, text completion, and image generation with local LLM models.

// Chat with AI
response, err := client.AI().Chat(ctx, scs.ChatInput{
    Message:      "What is the capital of France?",
    SystemPrompt: "You are a helpful geography assistant.",
})
fmt.Println(response.Content)

// Text completion
completion, err := client.AI().Complete(ctx, scs.CompleteInput{
    Prompt: "Once upon a time",
})
fmt.Println(completion.Content)

// Generate image
image, err := client.AI().GenerateImage(ctx, scs.GenerateImageInput{
    Prompt: "A sunset over mountains",
})
fmt.Println(image.ImageURL)

// List available models
models, err := client.AI().ListModels(ctx)

AI Agents

Create and manage AI agents with custom instructions and tools.

// Create an agent
temperature := 0.7
agent, err := client.AI().CreateAgent(ctx, scs.CreateAgentInput{
    Name:         "Customer Support",
    Instructions: "You are a helpful customer support assistant.",
    Model:        "llama3.2",
    Temperature:  &temperature,
})
fmt.Printf("Created agent: %s\n", agent.ID)

// List agents
agents, err := client.AI().ListAgents(ctx, 50, 0, "active")

// Run the agent
response, err := client.AI().RunAgent(ctx, agent.ID, scs.RunAgentInput{
    Input: "How do I reset my password?",
})
fmt.Printf("Agent: %s\n", response.Output)
fmt.Printf("Session: %s\n", response.SessionID)

// Continue the conversation in the same session
response, err = client.AI().RunAgent(ctx, agent.ID, scs.RunAgentInput{
    Input:     "Thanks! What about enabling 2FA?",
    SessionID: response.SessionID,
})

// List agent sessions
sessions, err := client.AI().ListAgentSessions(ctx, agent.ID, 50, 0)

// Get full session history
session, err := client.AI().GetAgentSession(ctx, agent.ID, response.SessionID)
for _, msg := range session.Messages {
    fmt.Printf("%s: %s\n", msg.Role, msg.Content)
}

// Update agent
newTemp := 0.5
updated, err := client.AI().UpdateAgent(ctx, agent.ID, scs.UpdateAgentInput{
    Instructions: "Updated instructions here",
    Temperature:  &newTemp,
})

// Define a tool for agents
tool, err := client.AI().DefineTool(ctx, scs.DefineToolInput{
    Name:        "get_weather",
    Description: "Get weather for a location",
    Parameters: map[string]interface{}{
        "type": "object",
        "properties": map[string]interface{}{
            "location": map[string]interface{}{
                "type":        "string",
                "description": "City name",
            },
        },
    },
})

// List tools
tools, err := client.AI().ListTools(ctx)

// Delete agent and sessions
err = client.AI().DeleteAgentSession(ctx, agent.ID, response.SessionID)
err = client.AI().DeleteAgent(ctx, agent.ID)

Realtime Database

// Connect to realtime database
err := client.Realtime().Connect(ctx)
defer client.Realtime().Disconnect()

// Get a reference
ref := client.Realtime().Ref("chat/messages")

// Set data
err := ref.Set(ctx, map[string]interface{}{
    "text":      "Hello!",
    "sender":    "user123",
    "timestamp": scs.ServerTimestamp(),
})

// Update data
err := ref.Update(ctx, map[string]interface{}{
    "text": "Updated message",
})

// Read data once
snapshot, err := ref.Get(ctx)
fmt.Printf("Data: %v\n", snapshot.Value)

// Listen for changes
err := ref.OnValue(func(event scs.RealtimeEvent) {
    fmt.Printf("Value changed: %v\n", event.Data)
})

// Listen for child events
err := ref.OnChildAdded(func(event scs.RealtimeEvent) {
    fmt.Printf("Child added at %s: %v\n", event.Path, event.Data)
})

// Remove listener
ref.Off("value")

// Delete data
err := ref.Remove(ctx)

// Transaction
err := ref.Transaction(ctx, func(current map[string]interface{}) (map[string]interface{}, error) {
    count := 0
    if c, ok := current["count"].(float64); ok {
        count = int(c)
    }
    current["count"] = count + 1
    return current, nil
})

Error Handling

The SDK provides typed errors for different failure scenarios:

result, err := client.Auth().Login(ctx, scs.LoginInput{
    Email:    "user@example.com",
    Password: "wrongpassword",
})
if err != nil {
    switch e := err.(type) {
    case *scs.AuthenticationError:
        fmt.Println("Invalid credentials")
    case *scs.ValidationError:
        fmt.Println("Invalid input:", e.Message)
    case *scs.NotFoundError:
        fmt.Println("Resource not found")
    case *scs.ForbiddenError:
        fmt.Println("Access denied")
    case *scs.ServerError:
        fmt.Println("Server error:", e.Message)
    default:
        fmt.Println("Unknown error:", err)
    }
}

Token Management

The SDK automatically manages authentication tokens:

// Token is automatically stored after login/register
client.Auth().Login(ctx, scs.LoginInput{...})

// You can also manually set/get/clear tokens
client.SetToken("your-jwt-token")
token := client.GetToken()
client.ClearToken()

Context Support

All methods accept a context.Context for cancellation and timeouts:

// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

doc, err := client.Database().Collection("users").Doc("123").Get(ctx)

// With cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
    // Cancel after some condition
    cancel()
}()

files, err := client.Storage().ListFiles(ctx)

Thread Safety

The SDK is designed to be thread-safe. You can share a single client instance across multiple goroutines:

client, _ := scs.NewClient(&scs.Config{...})

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        doc, _ := client.Database().Collection("users").Doc("123").Get(ctx)
        fmt.Println(doc.GetString("name"))
    }()
}
wg.Wait()

License

MIT License - see LICENSE file for details.

About

The official GoLang SDK for Spyxpo Cloud Services

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages