salesforce

package module
v2.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 19 Imported by: 0

README

Salesforce Go SDK

Go Go Reference Go Report Card Documentation

A comprehensive, production-ready Go SDK for Salesforce covering all major APIs.

View Full Documentation

Installation

go get github.com/PramithaMJ/salesforce

Features

  • Multiple Authentication Methods: OAuth 2.0 refresh token, username-password, and direct access token
  • Complete API Coverage:
    • SObject CRUD operations
    • SOQL queries with builder pattern
    • SOSL search with builder pattern
    • Bulk API 2.0 (ingest and query)
    • Composite API (batch, tree, graph, collections)
    • Analytics (Reports & Dashboards)
    • Tooling API (Apex, tests, metadata)
    • Connect/Chatter API
    • User Interface API
    • Apex REST endpoints
    • API Limits monitoring
  • Production Ready: Retry with exponential backoff, comprehensive error handling, context support

Quick Start

OAuth 2.0 Refresh Token
client, _ := salesforce.NewClient(
    salesforce.WithOAuthRefresh(
        os.Getenv("SF_CLIENT_ID"),
        os.Getenv("SF_CLIENT_SECRET"),
        os.Getenv("SF_REFRESH_TOKEN"),
    ),
)
client.Connect(context.Background())
Username-Password
client, _ := salesforce.NewClient(
    salesforce.WithCredentials(clientID, clientSecret),
    salesforce.WithPasswordAuth(username, password, securityToken),
)
client.Connect(context.Background())
Direct Access Token
client, _ := salesforce.NewClient(
    salesforce.WithAccessToken(accessToken, instanceURL),
)
client.SetAccessToken(accessToken, instanceURL)

Usage Examples

Query Records
// Simple query
result, _ := client.Query().Execute(ctx, "SELECT Id, Name FROM Account LIMIT 10")
for _, record := range result.Records {
    fmt.Println(record.StringField("Name"))
}

// Query builder
query := client.Query().NewBuilder("Contact").
    Select("Id", "FirstName", "LastName", "Email").
    WhereEquals("AccountId", accountID).
    OrderByAsc("LastName").
    Limit(50).
    Build()
result, _ := client.Query().Execute(ctx, query)
Create/Update Records
// Create
result, _ := client.SObjects().Create(ctx, "Account", map[string]interface{}{
    "Name": "Acme Corp",
    "Industry": "Technology",
})
fmt.Println("Created:", result.ID)

// Update
client.SObjects().Update(ctx, "Account", accountID, map[string]interface{}{
    "Description": "Updated description",
})

// Upsert by external ID
client.SObjects().Upsert(ctx, "Account", "External_ID__c", "EXT-001", data)
Bulk Operations
// Create bulk job
job, _ := client.Bulk().CreateJob(ctx, bulk.CreateJobRequest{
    Object:    "Account",
    Operation: bulk.OperationInsert,
})

// Upload data
client.Bulk().UploadCSV(ctx, job.ID, records, []string{"Name", "Industry"})

// Close and wait
client.Bulk().CloseJob(ctx, job.ID)
job, _ = client.Bulk().WaitForCompletion(ctx, job.ID, 5*time.Second)
Composite API
resp, _ := client.Composite().Execute(ctx, composite.Request{
    AllOrNone: true,
    CompositeRequest: []composite.Subrequest{
        {Method: "POST", URL: "/services/data/v59.0/sobjects/Account",
         ReferenceId: "newAccount", Body: map[string]interface{}{"Name": "New Account"}},
        {Method: "POST", URL: "/services/data/v59.0/sobjects/Contact",
         ReferenceId: "newContact", Body: map[string]interface{}{
             "LastName": "Smith", "AccountId": "@{newAccount.id}"}},
    },
})
Search (SOSL)
// Direct SOSL
result, _ := client.Search().Execute(ctx, "FIND {Acme} IN NAME FIELDS RETURNING Account(Id, Name)")

// Search builder
sosl := search.NewBuilder("Acme").
    In("NAME").
    ReturningWithFields("Account", "Id", "Name").
    ReturningWithFields("Contact", "Id", "FirstName", "LastName").
    Limit(20).
    Build()
result, _ := client.Search().Execute(ctx, sosl)
Tooling API
// Execute anonymous Apex
result, _ := client.Tooling().ExecuteAnonymous(ctx, `System.debug('Hello');`)

// Query Apex classes
classes, _ := client.Tooling().Query(ctx, "SELECT Id, Name FROM ApexClass LIMIT 10")
Analytics
// Run report
result, _ := client.Analytics().RunReport(ctx, reportID, true)

// List dashboards
dashboards, _ := client.Analytics().ListDashboards(ctx)
Chatter
// Get news feed
feed, _ := client.Chatter().GetNewsFeed(ctx)

// Post to feed
client.Chatter().PostFeedElement(ctx, connect.FeedInput{
    SubjectId: userID,
    Body: connect.MessageBodyInput{
        MessageSegments: []connect.MessageSegmentInput{
            {Type: "Text", Text: "Hello from Go SDK!"},
        },
    },
})
Limits
limits, _ := client.Limits().GetLimits(ctx)
fmt.Printf("API Requests: %d/%d (%.1f%% used)\n",
    limits.DailyApiRequests.Used(),
    limits.DailyApiRequests.Max,
    limits.DailyApiRequests.PercentUsed())
Apex REST
// Call custom Apex REST endpoint
var result MyResponse
client.Apex().GetJSON(ctx, "/MyEndpoint/v1/data", &result)

// POST to endpoint
client.Apex().PostJSON(ctx, "/MyEndpoint/v1/process", requestData, &result)

Configuration Options

Option Description
WithOAuthRefresh OAuth 2.0 refresh token flow
WithPasswordAuth Username-password flow
WithCredentials OAuth client credentials
WithAccessToken Direct access token
WithTokenURL Custom OAuth token endpoint
WithAPIVersion API version (default: 59.0)
WithTimeout HTTP timeout
WithMaxRetries Retry attempts (default: 3)
WithHTTPClient Custom HTTP client
WithLogger Custom logger
WithSandbox Use sandbox environment
WithCustomDomain My Domain configuration

Error Handling

result, err := client.SObjects().Get(ctx, "Account", "invalid-id")
if err != nil {
    if types.IsNotFoundError(err) {
        // Handle not found
    } else if types.IsAuthError(err) {
        // Handle auth error - maybe refresh token
    } else if types.IsRateLimitError(err) {
        // Handle rate limit - back off
    }
}

License

MIT License - see LICENSE

Documentation

Overview

Package salesforce provides a comprehensive Go SDK for Salesforce.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the main Salesforce API client.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient creates a new Salesforce client with the given options.

func (*Client) APIVersion

func (c *Client) APIVersion() string

APIVersion returns the configured API version.

func (*Client) Analytics

func (c *Client) Analytics() *analytics.Service

Analytics returns the Analytics/Reports service.

func (*Client) Apex

func (c *Client) Apex() *apex.Service

Apex returns the Apex REST service.

func (*Client) Bulk

func (c *Client) Bulk() *bulk.Service

Bulk returns the Bulk API 2.0 service.

func (*Client) Chatter

func (c *Client) Chatter() *connect.Service

Chatter returns the Connect/Chatter service.

func (*Client) Composite

func (c *Client) Composite() *composite.Service

Composite returns the Composite API service.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect authenticates and establishes connection to Salesforce.

func (*Client) GetToken

func (c *Client) GetToken() *types.Token

GetToken returns the current access token.

func (*Client) InstanceURL

func (c *Client) InstanceURL() string

InstanceURL returns the Salesforce instance URL.

func (*Client) Limits

func (c *Client) Limits() *limits.Service

Limits returns the Limits service.

func (*Client) Query

func (c *Client) Query() *query.Service

Query returns the Query service.

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context) error

RefreshToken refreshes the access token.

func (*Client) SObjects

func (c *Client) SObjects() *sobjects.Service

SObjects returns the SObject service.

func (*Client) Search

func (c *Client) Search() *search.Service

Search returns the SOSL Search service.

func (*Client) SetAccessToken

func (c *Client) SetAccessToken(token, instanceURL string)

SetAccessToken sets the access token directly.

func (*Client) Tooling

func (c *Client) Tooling() *tooling.Service

Tooling returns the Tooling API service.

func (*Client) UIAPI

func (c *Client) UIAPI() *uiapi.Service

UIAPI returns the User Interface API service.

type Config

type Config struct {
	// Authentication
	ClientID      string
	ClientSecret  string
	Username      string
	Password      string
	SecurityToken string
	RefreshToken  string
	AccessToken   string
	TokenURL      string
	InstanceURL   string

	// Connection
	APIVersion string
	Timeout    time.Duration
	MaxRetries int
	HTTPClient *http.Client
	Logger     types.Logger
}

Config holds the configuration for the Salesforce client.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type Option

type Option func(*Config) error

Option configures the Salesforce client.

func WithAPIVersion

func WithAPIVersion(version string) Option

WithAPIVersion sets the API version.

func WithAccessToken

func WithAccessToken(accessToken, instanceURL string) Option

WithAccessToken sets a direct access token.

func WithCredentials

func WithCredentials(clientID, clientSecret string) Option

WithCredentials sets OAuth client credentials.

func WithCustomDomain

func WithCustomDomain(domain string) Option

WithCustomDomain configures for a custom My Domain.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithInstanceURL

func WithInstanceURL(url string) Option

WithInstanceURL sets the Salesforce instance URL.

func WithLogger

func WithLogger(logger types.Logger) Option

WithLogger sets the logger.

func WithMaxRetries

func WithMaxRetries(retries int) Option

WithMaxRetries sets maximum retry attempts.

func WithOAuthRefresh

func WithOAuthRefresh(clientID, clientSecret, refreshToken string) Option

WithOAuthRefresh configures OAuth 2.0 refresh token authentication.

func WithPasswordAuth

func WithPasswordAuth(username, password, securityToken string) Option

WithPasswordAuth configures username-password authentication.

func WithSandbox

func WithSandbox() Option

WithSandbox configures for sandbox environment.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the HTTP timeout.

func WithTokenURL

func WithTokenURL(url string) Option

WithTokenURL sets the OAuth token endpoint URL.

Directories

Path Synopsis
Package analytics provides Reports and Dashboards API operations.
Package analytics provides Reports and Dashboards API operations.
Package apex provides Apex REST endpoint operations.
Package apex provides Apex REST endpoint operations.
Package auth provides authentication strategies for Salesforce.
Package auth provides authentication strategies for Salesforce.
Package bulk provides Bulk API 2.0 operations.
Package bulk provides Bulk API 2.0 operations.
Package composite provides Composite API operations.
Package composite provides Composite API operations.
Package connect provides Connect REST API (Chatter) operations.
Package connect provides Connect REST API (Chatter) operations.
Package http provides HTTP client functionality.
Package http provides HTTP client functionality.
Package limits provides API Limits operations.
Package limits provides API Limits operations.
Package query provides SOQL query execution and building.
Package query provides SOQL query execution and building.
Package search provides SOSL search operations.
Package search provides SOSL search operations.
Package sobjects provides SObject CRUD operations for Salesforce.
Package sobjects provides SObject CRUD operations for Salesforce.
Package tooling provides Tooling API operations.
Package tooling provides Tooling API operations.
Package types provides shared types for the Salesforce SDK.
Package types provides shared types for the Salesforce SDK.
Package uiapi provides User Interface API operations.
Package uiapi provides User Interface API operations.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL