salesforce

package module
v0.1.0 Latest Latest
Warning

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

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

README

Salesforce Go SDK

A production-grade Go SDK for Salesforce with OAuth 2.0 authentication support.

Installation

go get github.com/PramithaMJ/salesforce

Features

  • Multiple Authentication Methods: OAuth 2.0 refresh token, password flow, or direct token
  • Complete API Coverage: SObject CRUD, SOQL queries, Bulk API 2.0, Tooling API, Apex REST

Quick Start

package main

import (
    "context"
    "log"
    
    sf "github.com/PramithaMJ/salesforce"
)

func main() {
    client, err := sf.NewClient(
        sf.WithOAuthRefresh(
            "your-client-id",
            "your-client-secret", 
            "your-refresh-token",
        ),
        sf.WithTokenURL("https://login.salesforce.com/services/oauth2/token"),
    )
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }

    // Create a record
    account, err := client.SObjects().Create(ctx, "Account", map[string]interface{}{
        "Name": "Test Account",
    })
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Created account: %s", account.ID())

    // Query records
    result, err := client.Query().Execute(ctx, "SELECT Id, Name FROM Account LIMIT 10")
    if err != nil {
        log.Fatal(err)
    }
    for _, record := range result.Records {
        log.Printf("Account: %s - %s", record.ID(), record.StringField("Name"))
    }
}

Authentication Options

OAuth 2.0 Refresh Token
client, _ := sf.NewClient(
    sf.WithOAuthRefresh(clientID, clientSecret, refreshToken),
    sf.WithTokenURL("https://login.salesforce.com/services/oauth2/token"),
)
Username/Password
client, _ := sf.NewClient(
    sf.WithPasswordAuth(username, password, securityToken),
    sf.WithCredentials(clientID, clientSecret),
)
Direct Token
client, _ := sf.NewClient(
    sf.WithInstanceURL("https://yourinstance.salesforce.com"),
)
client.SetAccessToken(accessToken, instanceURL)

Query Builder

query := sf.NewQueryBuilder("Contact").
    Select("Id", "FirstName", "LastName", "Email").
    WhereEquals("AccountId", accountID).
    WhereLike("Email", "%@example.com").
    OrderByDesc("CreatedDate").
    Limit(100).
    Build()

result, _ := client.Query().Execute(ctx, query)

Bulk API 2.0

job, _ := client.Bulk().CreateJob(ctx, sf.CreateJobRequest{
    Object:    "Account",
    Operation: services.JobOperationInsert,
})
// Upload data, close job, wait for completion...

License

MIT License

Documentation

Overview

Package salesforce provides a comprehensive, production-grade Go SDK for Salesforce.

Index

Constants

View Source
const (
	DefaultAPIVersion = types.DefaultAPIVersion
	DefaultTimeout    = types.DefaultTimeout
	DefaultMaxRetries = types.DefaultMaxRetries
)

Re-export constants

View Source
const (
	ErrorCodeInvalidSession       = types.ErrorCodeInvalidSession
	ErrorCodeSessionExpired       = types.ErrorCodeSessionExpired
	ErrorCodeInvalidField         = types.ErrorCodeInvalidField
	ErrorCodeMalformedQuery       = types.ErrorCodeMalformedQuery
	ErrorCodeInvalidType          = types.ErrorCodeInvalidType
	ErrorCodeEntityDeleted        = types.ErrorCodeEntityDeleted
	ErrorCodeDuplicateValue       = types.ErrorCodeDuplicateValue
	ErrorCodeRequiredFieldMissing = types.ErrorCodeRequiredFieldMissing
	ErrorCodeInvalidCrossRef      = types.ErrorCodeInvalidCrossRef
	ErrorCodeInsufficientAccess   = types.ErrorCodeInsufficientAccess
	ErrorCodeRequestLimit         = types.ErrorCodeRequestLimit
	ErrorCodeStorageLimit         = types.ErrorCodeStorageLimit
)

Re-export error codes

Variables

View Source
var (
	ParseAPIError    = types.ParseAPIError
	IsNotFoundError  = types.IsNotFoundError
	IsAuthError      = types.IsAuthError
	IsRateLimitError = types.IsRateLimitError
)

Re-export helper functions

View Source
var NewQueryBuilder = services.NewQueryBuilder

NewQueryBuilder creates a new query builder.

View Source
var NewSObject = services.NewSObject

NewSObject creates a new SObject.

Functions

This section is empty.

Types

type APIError

type APIError = types.APIError

Re-export types for convenience

type APIErrors

type APIErrors = types.APIErrors

Re-export types for convenience

type APIVersionInfo

type APIVersionInfo struct {
	Label   string `json:"label"`
	URL     string `json:"url"`
	Version string `json:"version"`
}

APIVersionInfo represents a Salesforce API version.

type ApexService

type ApexService interface {
	Execute(ctx context.Context, method, path string, body interface{}) ([]byte, error)
}

ApexService defines operations for executing Apex REST endpoints.

type AuthError

type AuthError = types.AuthError

Re-export types for convenience

type Authenticator

type Authenticator interface {
	Authenticate(ctx context.Context) (*Token, error)
	Refresh(ctx context.Context) (*Token, error)
	IsTokenValid() bool
}

Authenticator defines the interface for authentication strategies.

type BulkService

type BulkService interface {
	CreateJob(ctx context.Context, req CreateJobRequest) (*JobInfo, error)
	UploadData(ctx context.Context, jobID string, data io.Reader) error
	CloseJob(ctx context.Context, jobID string) (*JobInfo, error)
	GetJobStatus(ctx context.Context, jobID string) (*JobInfo, error)
	GetSuccessfulRecords(ctx context.Context, jobID string) ([]map[string]interface{}, error)
	GetFailedRecords(ctx context.Context, jobID string) ([]FailedRecord, error)
	AbortJob(ctx context.Context, jobID string) (*JobInfo, error)
	DeleteJob(ctx context.Context, jobID string) error
}

BulkService defines operations for Bulk API 2.0.

type CompositeRequest

type CompositeRequest struct {
	AllOrNone        bool                  `json:"allOrNone"`
	CompositeRequest []CompositeSubrequest `json:"compositeRequest"`
}

CompositeRequest represents a composite API request.

type CompositeResponse

type CompositeResponse struct {
	CompositeResponse []CompositeSubresponse `json:"compositeResponse"`
}

CompositeResponse represents the response from a composite API request.

type CompositeSubrequest

type CompositeSubrequest struct {
	Method      string                 `json:"method"`
	URL         string                 `json:"url"`
	ReferenceId string                 `json:"referenceId"`
	Body        map[string]interface{} `json:"body,omitempty"`
}

CompositeSubrequest represents a single subrequest.

type CompositeSubresponse

type CompositeSubresponse struct {
	Body           interface{} `json:"body"`
	HTTPStatusCode int         `json:"httpStatusCode"`
	ReferenceId    string      `json:"referenceId"`
}

CompositeSubresponse represents a single subresponse.

type Config

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

	// Connection
	BaseURL     string
	InstanceURL string
	APIVersion  string
	Timeout     time.Duration

	// Retry settings
	MaxRetries   int
	RetryWaitMin time.Duration
	RetryWaitMax time.Duration

	// Advanced
	Logger     types.Logger
	HTTPClient *http.Client
	Debug      bool
}

Config holds the configuration for the Salesforce client.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with default values.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid.

type CreateJobRequest

type CreateJobRequest = services.CreateJobRequest

Re-export service types

type ErrorCode

type ErrorCode = types.ErrorCode

Re-export types for convenience

type ExecuteAnonymousResult

type ExecuteAnonymousResult = services.ExecuteAnonymousResult

Re-export service types

type FailedRecord

type FailedRecord = services.FailedRecord

Re-export service types

type GlobalDescribeResult

type GlobalDescribeResult = services.GlobalDescribeResult

Re-export service types

type JobInfo

type JobInfo = services.JobInfo

Re-export service types

type LimitInfo

type LimitInfo struct {
	Max       int `json:"Max"`
	Remaining int `json:"Remaining"`
}

LimitInfo contains limit details.

func (LimitInfo) PercentUsed

func (l LimitInfo) PercentUsed() float64

PercentUsed returns the percentage of limit used.

func (LimitInfo) Used

func (l LimitInfo) Used() int

Used returns the number of requests used.

type Limits

type Limits struct {
	DailyApiRequests LimitInfo `json:"DailyApiRequests"`
}

Limits represents Salesforce API limits.

type Logger

type Logger = types.Logger

Re-export types for convenience

type Option

type Option func(*Config)

Option is a functional option for configuring the client.

func WithAPIVersion

func WithAPIVersion(version string) Option

WithAPIVersion sets the Salesforce API version.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the base URL for authentication.

func WithCredentials

func WithCredentials(clientID, clientSecret string) Option

WithCredentials sets the OAuth client credentials.

func WithDebug

func WithDebug(debug bool) Option

WithDebug enables debug logging.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets the HTTP client.

func WithInstanceURL

func WithInstanceURL(instanceURL string) Option

WithInstanceURL sets the Salesforce instance URL.

func WithLogger

func WithLogger(logger types.Logger) Option

WithLogger sets the logger.

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 WithRetry

func WithRetry(maxRetries int, waitMin, waitMax time.Duration) Option

WithRetry configures retry behavior.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the HTTP timeout.

func WithTokenURL

func WithTokenURL(tokenURL string) Option

WithTokenURL sets the OAuth token endpoint URL.

type QueryBuilder

type QueryBuilder = services.QueryBuilder

Re-export service types

type QueryResult

type QueryResult = services.QueryResult

Re-export service types

type QueryService

type QueryService interface {
	Execute(ctx context.Context, query string) (*QueryResult, error)
	ExecuteAll(ctx context.Context, query string) (*QueryResult, error)
	QueryMore(ctx context.Context, nextRecordsURL string) (*QueryResult, error)
	NewBuilder(objectType string) *QueryBuilder
}

QueryService defines operations for SOQL queries.

type RateLimitError

type RateLimitError = types.RateLimitError

Re-export types for convenience

type SObject

type SObject = services.SObject

Re-export service types

type SObjectMetadata

type SObjectMetadata = services.SObjectMetadata

Re-export service types

type SObjectService

type SObjectService interface {
	Create(ctx context.Context, objectType string, data map[string]interface{}) (*SObject, error)
	Get(ctx context.Context, objectType, id string, fields ...string) (*SObject, error)
	Update(ctx context.Context, objectType, id string, data map[string]interface{}) error
	Upsert(ctx context.Context, objectType, externalIDField, externalID string, data map[string]interface{}) (*SObject, error)
	Delete(ctx context.Context, objectType, id string) error
	Describe(ctx context.Context, objectType string) (*SObjectMetadata, error)
	DescribeGlobal(ctx context.Context) (*GlobalDescribeResult, error)
}

SObjectService defines operations on Salesforce SObjects.

type SalesforceClient

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

SalesforceClient is the main client for interacting with Salesforce.

func NewClient

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

NewClient creates a new Salesforce client with the given options.

func (*SalesforceClient) APIVersion

func (c *SalesforceClient) APIVersion() string

APIVersion returns the API version being used.

func (*SalesforceClient) Apex

func (c *SalesforceClient) Apex() ApexService

Apex returns the Apex REST service.

func (*SalesforceClient) ApexREST

func (c *SalesforceClient) ApexREST(ctx context.Context, method, path string, body io.Reader) ([]byte, error)

ApexREST makes a request to a custom Apex REST endpoint.

func (*SalesforceClient) Bulk

func (c *SalesforceClient) Bulk() BulkService

Bulk returns the Bulk API service.

func (*SalesforceClient) Close

func (c *SalesforceClient) Close() error

Close cleans up any resources held by the client.

func (*SalesforceClient) Connect

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

Connect authenticates and establishes connection to Salesforce.

func (*SalesforceClient) ExecuteComposite

func (c *SalesforceClient) ExecuteComposite(ctx context.Context, req CompositeRequest) (*CompositeResponse, error)

ExecuteComposite executes a composite request.

func (*SalesforceClient) GetLimits

func (c *SalesforceClient) GetLimits(ctx context.Context) (*Limits, error)

GetLimits retrieves the current API limits for the org.

func (*SalesforceClient) GetToken

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

GetToken returns the current token (implements TokenProvider).

func (*SalesforceClient) GetVersions

func (c *SalesforceClient) GetVersions(ctx context.Context) ([]APIVersionInfo, error)

GetVersions retrieves available API versions.

func (*SalesforceClient) InstanceURL

func (c *SalesforceClient) InstanceURL() string

InstanceURL returns the Salesforce instance URL.

func (*SalesforceClient) Query

func (c *SalesforceClient) Query() QueryService

Query returns the Query service.

func (*SalesforceClient) RefreshToken

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

RefreshToken refreshes the access token (implements TokenProvider).

func (*SalesforceClient) SObjects

func (c *SalesforceClient) SObjects() SObjectService

SObjects returns the SObject service.

func (*SalesforceClient) SetAccessToken

func (c *SalesforceClient) SetAccessToken(accessToken, instanceURL string)

SetAccessToken sets the access token directly.

func (*SalesforceClient) Tooling

func (c *SalesforceClient) Tooling() ToolingService

Tooling returns the Tooling API service.

type Token

type Token = types.Token

Re-export types for convenience

type ToolingService

type ToolingService interface {
	Query(ctx context.Context, query string) (*QueryResult, error)
	ExecuteAnonymous(ctx context.Context, apexCode string) (*ExecuteAnonymousResult, error)
	Describe(ctx context.Context, objectType string) (*SObjectMetadata, error)
}

ToolingService defines operations for the Tooling API.

type ValidationError

type ValidationError = types.ValidationError

Re-export types for convenience

Directories

Path Synopsis
Package types contains shared types for the Salesforce SDK to avoid import cycles.
Package types contains shared types for the Salesforce SDK to avoid import cycles.

Jump to

Keyboard shortcuts

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