callr

package module
v2.0.0-rc4 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2025 License: MIT Imports: 12 Imported by: 0

README

sdk-go

SDK in Go for the Callr API.

Works with Go 1.22+, using standard packages only.

Quick start

import callr "github.com/THECALLR/sdk-go/v2"

func main() {
    // Api Key Auth (use the customer portal to generate keys)
    api := callr.New("key")
    
    result, err := api.Call(context.Background(), "method", params...)

Usage

Login-As

If you have sub accounts and want to manage them with your master account, you can use the Login-As feature.

import callr "github.com/THECALLR/sdk-go/v2"

func main() {
    // Api Key Auth (use the customer portal to generate keys)
    api := callr.New("key") // master account key

    if err := api.SetLoginAsSubAccountRef("<subAccountRef>"); err != nil {
        log.Fatalf("[error] cannot login as: %s\n", err)
    }

    // all following calls will be done as the sub account
    result, err := api.Call(context.Background(), "method", params...)
Return and error handling

The SDK returns a json.RawMessage, which can be unmarshalled to the expected type, or an error. The error may be of type *JSONRPCError if the error comes from the API, of type *HTTPError if the error comes from the HTTP transport, or a native error otherwise.

	result, err := api.Call(ctx, "sms.send", "SMS", os.Args[1], "Hello, world", nil)

	// error management
	if err != nil {
		switch e := err.(type) {
		case *callr.JSONRPCError:
			slog.Error("JSON-RPC Error",
				"code", e.Code,
				"message", e.Message,
				"data", e.Data)
		case *callr.HTTPError:
			slog.Error("HTTP Error",
				"code", e.Code,
				"message", e.Message)
		default:
			slog.Error("Other error", "error", err)
		}
		os.Exit(1)
	}

	// the sms.send JSON-RPC method returns a string
	var hash string

	if err := json.Unmarshal(result, &hash); err != nil {
		slog.Error("Error unmarshalling result", "error", err)
		os.Exit(1)
	}

	slog.Info("SMS sent", "hash", hash)

Documentation

Overview

Package callr implements the Callr API, using JSON-RPC 2.0. See https://www.callr.com/ and https://www.callr.com/docs/.

Requires Go 1.22+, using standard packages only.

Note: This package may emit logs when errors occur when communicating with the API. The default logging function is log.Printf from the standard library. You can change the logging function with SetLogFunc.

Usage:

package main

import (
  "context"
  "encoding/json"
  "fmt"
  "log/slog"
  "os"
  "strings"

  callr "github.com/THECALLR/sdk-go/v2"
)

func main() {
  // optional: use slog instead of log.Printf
  callr.SetLogFunc(func(format string, args ...any) {
    slog.Warn(fmt.Sprintf(strings.TrimPrefix(format, "[warning] "), args...))
  })

  // Api Key Auth (use the customer portal to generate keys)
  api := callr.New(os.Getenv("CALLR_API_KEY"))

  // optional: pass an http.Client with custom settings (ie proxy)
  // api := callr.NewWithHttpClient(os.Getenv("CALLR_API_KEY"), &http.Client{})

  // check for destination phone number parameter
  if len(os.Args) < 2 {
    // fmt.Println("Please supply destination phone number!")
    slog.Error("Please supply destination phone number!")
    os.Exit(1)
  }

  // our context
  ctx := context.Background()

  // Send a SMS with "sms.send" JSON-RPC method
  result, err := api.Call(ctx, "sms.send", "SMS", os.Args[1], "Hello, world", nil)

  // error management
  if err != nil {
    switch e := err.(type) {
    case *callr.JSONRPCError:
      slog.Error("JSON-RPC Error",
        "code", e.Code,
        "message", e.Message,
        "data", e.Data)
    case *callr.HTTPError:
      slog.Error("HTTP Error",
        "code", e.Code,
        "message", e.Message)
    default:
      slog.Error("Other error", "error", err)
    }
    os.Exit(1)
  }

  // the sms.send JSON-RPC method returns a string
  var hash string

  if err := json.Unmarshal(result, &hash); err != nil {
    slog.Error("Error unmarshalling result", "error", err)
    os.Exit(1)
  }

  slog.Info("SMS sent", "hash", hash)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetLogFunc

func SetLogFunc(fn LogFunc)

SetLogFunc can be used to change the default logger (log.Printf). Set to nil to disable package logging.

Types

type API

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

API represents a connection to the Callr API.

func New

func New(key string) *API

New returns an API object with API Key Authentication.

func (*API) Call

func (api *API) Call(ctx context.Context, method string, params ...any) (json.RawMessage, error)

Call sends a JSON-RPC 2.0 request to the Callr API, and returns either a result or an error. The error may be of type *JSONRPCError if the error comes from the API, of type *HTTPError if the error comes from the HTTP transport, or a native error otherwise.

func (*API) HookPreRequest

func (api *API) HookPreRequest(f ...PreRequestFunc)

HookPreRequest allows you to add a function that will be called before each request to the API.

func (*API) NewWithHttpClient

func (api *API) NewWithHttpClient(key string, client *http.Client) *API

NewWithHttpClient returns an API object with API Key Authentication and a custom http.Client.

func (*API) ResetLoginAs

func (api *API) ResetLoginAs()

ResetLoginAs removes the login-as configuration.

func (*API) SetLoginAs

func (api *API) SetLoginAs(targetType LoginAsType, value string) error

SetLoginAs allows you to connect to the API as a sub account of yours, using different target types.

func (*API) SetLoginAsSubAccountLogin

func (api *API) SetLoginAsSubAccountLogin(userLogin string) error

SetLoginAsSubAccountLogin allows you to connect to the API as a sub-account of yours, using the sub-account user "login" field.

func (*API) SetLoginAsSubAccountRef

func (api *API) SetLoginAsSubAccountRef(accountRef string) error

SetLoginAsSubAccountRef allows you to connect to the API as a sub-account of yours, using the sub-account "ref" field (sometimes called "hash").

func (*API) SetURL

func (api *API) SetURL(url string)

SetURL changes the URL for the API object

func (*API) SetURLs

func (api *API) SetURLs(urls []string) error

SetURLs sets multiple URL for the API object. One URL is randomly selected when querying the API.

type HTTPError

type HTTPError struct {
	Code    int
	Message string
}

HTTPError is an HTTP error with a code and a message. It satisfies the native error interface.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface. Returns a string with the Code and Message properties.

type JSONRPCError

type JSONRPCError struct {
	Code    int64  `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
}

JSONRPCError is a JSON-RPC 2.0 error, returned by the API. It satisfies the native error interface.

func (*JSONRPCError) Error

func (e *JSONRPCError) Error() string

Error implements the error interface. Returns a string with the Code and Message properties.

type JSONRPCRequest

type JSONRPCRequest struct {
	ID      int64  `json:"id"`
	JSONRPC string `json:"jsonrpc"`
	Method  string `json:"method"`
	Params  []any  `json:"params"`
}

type LogFunc

type LogFunc func(string, ...any) // Printf style

type LoginAsType

type LoginAsType string
const (
	LoginAsAccountID   LoginAsType = "account.id"
	LoginAsAccountRef  LoginAsType = "account.hash"
	LoginAsAccountHash LoginAsType = "account.hash"
	LoginAsUserID      LoginAsType = "user.id"
	LoginAsUserLogin   LoginAsType = "user.login"
)

type PreRequestFunc

type PreRequestFunc func(context.Context, *http.Client, *http.Request, *JSONRPCRequest)

PreRequestFunc is a function that can be added to the API object to be called before each request.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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