common

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2025 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package common provides shared utilities and types for the ARK SDK.

This package implements a comprehensive HTTP client with features like: - Authentication support (token-based, basic auth) - Cookie management with persistent storage - Automatic token refresh capabilities - Request/response logging - TLS configuration options

The ArkClient is the primary interface for making HTTP requests to Ark services, providing a consistent and feature-rich HTTP client implementation.

Package common provides shared utilities and types for the ARK SDK.

This package implements a custom logger with configurable log levels, color-coded output, and environment variable support for configuration.

Package common provides shared utilities and types for the ARK SDK.

This package contains shared types and functionality used across the Ark SDK, including pagination support and common data structures for API responses.

Package common provides random utility functions for generating secure passwords, random strings, IP addresses, and other randomized data used throughout the ARK SDK.

This package includes both cryptographically secure random generation using crypto/rand and pseudo-random generation using math/rand for different use cases.

Package common provides JSON serialization and deserialization utilities for the ARK SDK.

This package handles conversion between different JSON key naming conventions (camelCase and snake_case) and provides utilities for serializing/deserializing JSON data with optional schema validation. It supports both simple conversions and schema-aware transformations that preserve specific field mappings based on struct tags.

Package common provides shared utilities and types for the ARK SDK.

This package handles configuration for colored output, interactive mode, certificate verification, output control, logging levels, and trusted certificates. It provides a centralized way to control various system behaviors through global state and environment variables.

Package common provides shared utilities and types for the ARK SDK.

This package handles user agent string generation for HTTP requests made by the ARK SDK, combining browser user agent strings with SDK version information to provide proper identification in network communications.

Package common provides shared utilities and types for the ARK SDK.

This package handles version information storage and retrieval for the ARK SDK, providing a centralized way to manage and access the current SDK version throughout the application lifecycle.

Index

Constants

View Source
const (
	Debug    = 4
	Info     = 3
	Warning  = 2
	Error    = 1
	Critical = 0
	Unknown  = -1
)

Log level constants for ArkLogger.

These constants define the severity levels used by the logging system. Higher numbers indicate more verbose output (Debug=4 is most verbose, Critical=0 is least verbose).

View Source
const (
	LoggerStyle        = "LOGGER_STYLE"
	LogLevel           = "LOG_LEVEL"
	LoggerStyleDefault = "default"
)

Environment variable names for logger configuration.

These constants define the environment variables that can be used to configure the logger behavior at runtime.

View Source
const (
	ArkDisableCertificateVerificationEnvVar = "ARK_DISABLE_CERTIFICATE_VERIFICATION"
)

ArkDisableCertificateVerificationEnvVar is the environment variable name for disabling certificate validation.

When this environment variable is set to any non-empty value, certificate verification will be disabled regardless of the internal isCertificateVerification setting.

Variables

View Source
var GlobalLogger = GetLogger("ark-sdk", -1)

GlobalLogger is the global logger instance for the Ark SDK.

This variable provides a package-level logger that can be used throughout the Ark SDK. It is configured to resolve its log level from the LOG_LEVEL environment variable and uses "ark-sdk" as its prefix.

Example:

common.GlobalLogger.Info("SDK operation completed")

Functions

func AllowOutput

func AllowOutput()

AllowOutput allows output to be displayed.

AllowOutput sets the global isAllowingOutput flag to true, enabling the application to display output messages, logs, and other information to the console or other output destinations.

Example:

AllowOutput()
if IsAllowingOutput() {
    fmt.Println("This message will be displayed")
}

func ArkVersion added in v1.4.1

func ArkVersion() string

ArkVersion returns the current version of the Ark SDK.

ArkVersion retrieves the currently stored SDK version string. The default version is "0.0.0" if no version has been explicitly set using SetArkVersion.

Returns the current SDK version string.

Example:

version := ArkVersion()
fmt.Printf("Current SDK version: %s\n", version)

func ConvertToCamelCase added in v1.4.1

func ConvertToCamelCase(data interface{}, schema *reflect.Type) interface{}

ConvertToCamelCase converts a map with snake_case keys to camelCase keys.

ConvertToCamelCase recursively processes data structures, converting all string keys from snake_case to camelCase format. It supports nested maps, slices, and arbitrary data types. When a schema is provided, it uses struct field information to determine whether specific fields should be converted or preserved as-is (e.g., for map fields with string keys that should not be converted).

Parameters:

  • data: The data structure to convert (supports maps, slices, and primitive types)
  • schema: Optional reflect.Type pointer for schema-aware conversion (nil for simple conversion)

Returns the converted data structure with camelCase keys.

Example:

input := map[string]interface{}{"first_name": "John", "last_name": "Doe"}
result := ConvertToCamelCase(input, nil)
// result: map[string]interface{}{"firstName": "John", "lastName": "Doe"}

func ConvertToSnakeCase added in v1.4.1

func ConvertToSnakeCase(data interface{}, schema *reflect.Type) interface{}

ConvertToSnakeCase converts a map with camelCase keys to snake_case keys.

ConvertToSnakeCase recursively processes data structures, converting all string keys from camelCase to snake_case format. It supports nested maps, slices, and arbitrary data types. When a schema is provided, it uses struct field information to determine whether specific fields should be converted or preserved as-is (e.g., for map fields with string keys that should not be converted).

Parameters:

  • data: The data structure to convert (supports maps, slices, and primitive types)
  • schema: Optional reflect.Type pointer for schema-aware conversion (nil for simple conversion)

Returns the converted data structure with snake_case keys.

Example:

input := map[string]interface{}{"firstName": "John", "lastName": "Doe"}
result := ConvertToSnakeCase(input, nil)
// result: map[string]interface{}{"first_name": "John", "last_name": "Doe"}

func DeserializeJSONSnake

func DeserializeJSONSnake(response io.ReadCloser) (interface{}, error)

DeserializeJSONSnake takes an io.ReadCloser response and deserializes it into a map with snake_case keys.

DeserializeJSONSnake reads JSON data from the provided io.ReadCloser, parses it, and converts all keys from the original format to snake_case. This function is useful for normalizing JSON responses that may have keys in camelCase or other formats to a consistent snake_case format.

Parameters:

  • response: The io.ReadCloser containing JSON data to deserialize

Returns the deserialized data with snake_case keys and any error encountered during JSON decoding.

Example:

data, err := DeserializeJSONSnake(httpResponse.Body)
if err != nil {
    log.Fatal(err)
}
// data contains the JSON with snake_case keys

func DeserializeJSONSnakeSchema added in v1.4.1

func DeserializeJSONSnakeSchema(response io.ReadCloser, schema *reflect.Type) (interface{}, error)

DeserializeJSONSnakeSchema takes an io.ReadCloser response and deserializes it into a map with snake_case keys.

DeserializeJSONSnakeSchema reads JSON data from the provided io.ReadCloser, parses it, and converts all keys from the original format to snake_case using schema-aware conversion. The schema parameter allows for more intelligent key conversion by considering struct field types and tags, which helps preserve certain fields (like maps with string keys) that should not be converted.

Parameters:

  • response: The io.ReadCloser containing JSON data to deserialize
  • schema: Pointer to reflect.Type for schema-aware conversion (can be nil)

Returns the deserialized data with snake_case keys and any error encountered during JSON decoding.

Example:

var schemaType reflect.Type = reflect.TypeOf(MyStruct{})
data, err := DeserializeJSONSnakeSchema(httpResponse.Body, &schemaType)
if err != nil {
    log.Fatal(err)
}
// data contains the JSON with schema-aware snake_case keys

func DisableCertificateVerification

func DisableCertificateVerification()

DisableCertificateVerification disables certificate verification.

DisableCertificateVerification sets the global isCertificateVerification flag to false, disabling SSL/TLS certificate validation for network connections. This should be used with caution as it reduces security.

Example:

DisableCertificateVerification()
if IsVerifyingCertificates() {
    // This block will not execute
}

func DisableColor

func DisableColor()

DisableColor disables colored output in the console.

DisableColor sets the global noColor flag to true, which will cause IsColoring() to return false. This affects all subsequent console output that checks for color support throughout the application.

Example:

DisableColor()
if IsColoring() {
    // This block will not execute
}

func DisableInteractive

func DisableInteractive()

DisableInteractive disables interactive mode.

DisableInteractive sets the global isInteractive flag to false, preventing the application from displaying interactive prompts or requiring user input. This is useful for automated scripts or CI/CD environments.

Example:

DisableInteractive()
if IsInteractive() {
    // This block will not execute
}

func DisableVerboseLogging

func DisableVerboseLogging()

DisableVerboseLogging disables verbose logging.

DisableVerboseLogging sets the LogLevel environment variable to "CRITICAL", effectively reducing the logging output to only critical messages.

Example:

DisableVerboseLogging()
// Only critical log messages will be displayed

func DisallowOutput

func DisallowOutput()

DisallowOutput disallows output to be displayed.

DisallowOutput sets the global isAllowingOutput flag to false, preventing the application from displaying output. This is useful for silent operation modes or when output needs to be suppressed.

Example:

DisallowOutput()
if IsAllowingOutput() {
    // This block will not execute
}

func EnableCertificateVerification

func EnableCertificateVerification()

EnableCertificateVerification enables certificate verification.

EnableCertificateVerification sets the global isCertificateVerification flag to true, enabling SSL/TLS certificate validation for network connections. Note that if the ArkDisableCertificateVerificationEnvVar environment variable is set, certificate verification will still be disabled.

Example:

EnableCertificateVerification()
if IsVerifyingCertificates() {
    // Certificates will be verified
}

func EnableColor

func EnableColor()

EnableColor enables colored output in the console.

EnableColor sets the global noColor flag to false, which will cause IsColoring() to return true. This enables colored console output throughout the application.

Example:

EnableColor()
if IsColoring() {
    // This block will execute, allowing colored output
}

func EnableInteractive

func EnableInteractive()

EnableInteractive enables interactive mode.

EnableInteractive sets the global isInteractive flag to true, allowing the application to prompt for user input and display interactive elements.

Example:

EnableInteractive()
if IsInteractive() {
    // Show interactive prompts
}

func EnableVerboseLogging

func EnableVerboseLogging(logLevel string)

EnableVerboseLogging enables verbose logging with the specified log level.

EnableVerboseLogging sets the LogLevel environment variable to the provided log level string. If an empty string is provided, it defaults to "DEBUG". This affects the logging verbosity throughout the application.

Parameters:

  • logLevel: The desired log level string (defaults to "DEBUG" if empty)

Example:

EnableVerboseLogging("INFO")
EnableVerboseLogging("") // Uses "DEBUG" as default

func ExpandFolder

func ExpandFolder(folder string) string

ExpandFolder expands the given folder path by replacing environment variables and user home directory.

This function performs path expansion by handling environment variables ($VAR || ${VAR}) and tilde (~) expansion for user home directories. It ensures the returned path ends with a trailing slash for consistency. If the path starts with ~/ or is exactly ~/, it replaces the tilde portion with the current user's home directory.

The function processes the input in the following order: 1. Expands environment variables using os.ExpandEnv 2. Adds trailing slash if not present 3. Performs tilde expansion if path starts with ~/ or is exactly ~

Note: The function has some quirks in its current implementation: - Returns empty string if user lookup fails during tilde expansion

Parameters:

  • folder: The folder path to expand (can contain environment variables and ~/)

Returns the expanded folder path with trailing slash, or empty string if user lookup fails.

Example:

expanded := ExpandFolder("~/Documents")        // Returns "/Users/username/Documents" (no trailing slash due to filepath.Join)
expanded := ExpandFolder("$HOME/config")       // Returns "/Users/username/config/"
expanded := ExpandFolder("/absolute/path")     // Returns "/absolute/path/"
expanded := ExpandFolder("~")                  // Returns "/Users/username/"

func IsAllowingOutput

func IsAllowingOutput() bool

IsAllowingOutput checks if output is allowed to be displayed.

IsAllowingOutput returns true when the application is permitted to display output messages and false when output should be suppressed.

Returns true if output is allowed, false otherwise.

Example:

if IsAllowingOutput() {
    logger.Info("Operation completed successfully")
}

func IsColoring

func IsColoring() bool

IsColoring checks if colored output is enabled.

IsColoring returns true when colored output is enabled (noColor is false) and false when colored output is disabled. This function is used throughout the application to determine whether to apply color formatting to console output.

Returns true if colored output is enabled, false otherwise.

Example:

if IsColoring() {
    fmt.Print("\033[31mRed text\033[0m")
} else {
    fmt.Print("Plain text")
}

func IsConnectionRefused

func IsConnectionRefused(err error) bool

IsConnectionRefused checks if the error is a connection refused error.

This function examines an error to determine if it represents a connection refused condition. It handles nested error types including net.OpError and os.SyscallError to properly detect ECONNREFUSED errors at any level.

Parameters:

  • err: The error to examine (can be nil)

Returns true if the error represents a connection refused condition, false otherwise.

Example:

conn, err := net.Dial("tcp", "localhost:8080")
if err != nil && IsConnectionRefused(err) {
    log.Println("Service is not running")
}

func IsInteractive

func IsInteractive() bool

IsInteractive checks if interactive mode is enabled.

IsInteractive returns true when the application is allowed to display interactive prompts and request user input, and false when running in non-interactive mode (suitable for automation).

Returns true if interactive mode is enabled, false otherwise.

Example:

if IsInteractive() {
    response := promptUser("Continue? (y/n): ")
}

func IsVerifyingCertificates

func IsVerifyingCertificates() bool

IsVerifyingCertificates checks if certificate verification is enabled.

IsVerifyingCertificates returns false if the ArkDisableCertificateVerificationEnvVar environment variable is set to any non-empty value, regardless of the internal isCertificateVerification setting. Otherwise, it returns the value of the isCertificateVerification flag.

Returns true if certificate verification is enabled, false otherwise.

Example:

if IsVerifyingCertificates() {
    // Use secure connection with certificate validation
} else {
    // Use connection without certificate validation
}

func LogLevelFromEnv

func LogLevelFromEnv() int

LogLevelFromEnv retrieves the log level from the LOG_LEVEL environment variable.

This function reads the LOG_LEVEL environment variable and converts it to the corresponding integer log level. If the environment variable is not set or empty, it defaults to Critical level.

Returns the integer log level corresponding to the environment variable value, or Critical (0) if the variable is not set or contains an invalid value.

Example:

os.Setenv("LOG_LEVEL", "DEBUG")
level := LogLevelFromEnv() // Returns 4 (Debug)

func MarshalCookies

func MarshalCookies(cookieJar *cookiejar.Jar) ([]byte, error)

MarshalCookies serializes a cookie jar into a JSON byte array.

This function converts all cookies from a cookiejar.Jar into a JSON-serializable format, enabling persistent storage of cookie state. The resulting byte array can be stored to disk or transmitted over networks for session persistence.

Note: This implementation uses the AllCookies() method from persistent-cookiejar which provides direct access to all stored cookies.

Parameters:

  • cookieJar: The cookie jar containing cookies to be marshaled

Returns the JSON byte array representation of all cookies, or an error if JSON marshaling fails.

Example:

cookieData, err := MarshalCookies(client.GetCookieJar())
if err != nil {
    // handle error
}
// Save cookieData to file or database

func RandomIPAddress

func RandomIPAddress() string

RandomIPAddress generates a random IPv4 address using pseudo-random number generation.

RandomIPAddress creates a random IPv4 address by generating a random 32-bit unsigned integer and converting it to IPv4 format. This function uses math/rand for generation, making it suitable for testing and non-cryptographic purposes.

Returns a string representation of a random IPv4 address in dotted decimal notation.

Example:

ip := RandomIPAddress()
// ip might be "192.168.1.100" or any other valid IPv4 address

func RandomNumberString

func RandomNumberString(n int) string

RandomNumberString generates a random string of digits of specified length.

RandomNumberString creates a random string containing only numeric digits (0-9). This function uses math/rand for generation, making it suitable for testing and non-cryptographic purposes where predictable randomness is acceptable.

Parameters:

  • n: The desired length of the generated numeric string (must be >= 0)

Returns a random string of length n containing only digits from [0-9].

Example:

numStr := RandomNumberString(6)
// numStr might be "123456" or any other 6-digit numeric string

func RandomPassword

func RandomPassword(n int) string

RandomPassword generates a cryptographically secure random password of specified length.

RandomPassword creates a password that contains at least one digit, one lowercase letter, and one uppercase letter. The remaining characters are randomly selected from the full character set. The password is then shuffled to randomize character positions. This function uses crypto/rand for secure random generation.

Parameters:

  • n: The desired length of the generated password (must be >= 3)

Returns a random password of length n that meets complexity requirements. Panics if n < 3 since a secure password requires at least one character from each required character class.

Example:

password := RandomPassword(12)
// password might be "A7b9X2mN5qP1" with guaranteed character diversity

func RandomString

func RandomString(n int) string

RandomString generates a random string of specified length using alphanumeric characters.

RandomString creates a random string containing uppercase letters, lowercase letters, and digits. This function uses math/rand for generation, making it suitable for testing and non-cryptographic purposes where predictable randomness is acceptable.

Parameters:

  • n: The desired length of the generated string (must be >= 0)

Returns a random string of length n containing characters from [a-zA-Z0-9].

Example:

str := RandomString(10)
// str might be "aBc123XyZ9" or any other 10-character alphanumeric string

func RetryCall

func RetryCall(
	fn func() error,
	tries int,
	delay int,
	maxDelay *int,
	backoff int,
	jitter interface{},
	logger func(error, int),
) error

RetryCall executes a function with retry logic using exponential backoff.

The function will be retried up to 'tries' times with an initial delay of 'delay' seconds. After each failed attempt, the delay is multiplied by 'backoff' and optional jitter is added. If maxDelay is specified, the delay will not exceed this value.

Parameters:

  • fn: The function to execute and retry on failure
  • tries: Maximum number of attempts (must be > 0)
  • delay: Initial delay between retries in seconds
  • maxDelay: Optional maximum delay cap in seconds (nil for no limit)
  • backoff: Multiplier applied to delay after each attempt
  • jitter: Additional delay randomization - either fixed int or [2]int range
  • logger: Optional callback to log retry attempts (receives error and current delay)

Returns nil on success, or the last error encountered if all retries are exhausted.

Example:

err := RetryCall(
    func() error { return someOperation() },
    3,     // max 3 attempts
    1,     // start with 1 second delay
    &10,   // cap at 10 seconds
    2,     // double delay each time
    [2]int{0, 500}, // add 0-500ms jitter
    func(err error, delay int) { log.Printf("Retry in %ds: %v", delay, err) },
)

func SerializeJSONCamel

func SerializeJSONCamel(item interface{}) (map[string]interface{}, error)

SerializeJSONCamel takes an interface and serializes it into a map with camelCase keys.

SerializeJSONCamel converts the provided data structure to JSON, then parses it back into a map with all keys converted to camelCase format. This function is useful for preparing data for APIs or systems that expect camelCase key naming conventions.

Parameters:

  • item: The data structure to serialize (must be JSON-serializable)

Returns a map with camelCase keys and any error encountered during JSON marshaling or unmarshaling.

Example:

input := struct{ FirstName string }{FirstName: "John"}
result, err := SerializeJSONCamel(input)
if err != nil {
    log.Fatal(err)
}
// result: map[string]interface{}{"firstName": "John"}

func SerializeJSONCamelSchema added in v1.4.1

func SerializeJSONCamelSchema(item interface{}, schema *reflect.Type) (map[string]interface{}, error)

SerializeJSONCamelSchema takes an interface and serializes it into a map with camelCase keys.

SerializeJSONCamelSchema converts the provided data structure to JSON, then parses it back into a map with all keys converted to camelCase format using schema-aware conversion. The schema parameter allows for more intelligent key conversion by considering struct field types and tags, which helps preserve certain fields (like maps with string keys) that should not be converted.

Parameters:

  • item: The data structure to serialize (must be JSON-serializable)
  • schema: Pointer to reflect.Type for schema-aware conversion (can be nil)

Returns a map with camelCase keys and any error encountered during JSON marshaling or unmarshaling.

Example:

var schemaType reflect.Type = reflect.TypeOf(MyStruct{})
input := struct{ FirstName string }{FirstName: "John"}
result, err := SerializeJSONCamelSchema(input, &schemaType)
if err != nil {
    log.Fatal(err)
}
// result: map[string]interface{}{"firstName": "John"}

func SerializeResponseToJSON

func SerializeResponseToJSON(response io.ReadCloser) string

SerializeResponseToJSON takes an io.ReadCloser response and serializes it to a JSON string.

SerializeResponseToJSON reads all data from the provided io.ReadCloser, attempts to parse it as JSON, and returns a properly formatted JSON string. If the input data is not valid JSON, it returns the original data as a string. This function is useful for normalizing response data into a consistent JSON format.

Parameters:

  • response: The io.ReadCloser containing the response data to serialize

Returns a JSON string representation of the response data, or the original data as a string if JSON parsing fails.

Example:

jsonStr := SerializeResponseToJSON(httpResponse.Body)
fmt.Println(jsonStr) // Outputs properly formatted JSON

func SetArkVersion added in v1.4.1

func SetArkVersion(version string)

SetArkVersion sets the version of the Ark SDK.

SetArkVersion updates the global arkVersion variable with the provided version string. If an empty string is provided, the version remains unchanged. This function is typically called during application initialization to set the correct SDK version.

Parameters:

  • version: The version string to set (empty string is ignored)

Example:

SetArkVersion("1.2.3")
fmt.Println(ArkVersion()) // Outputs: 1.2.3

SetArkVersion("") // No change
fmt.Println(ArkVersion()) // Still outputs: 1.2.3

func SetLoggerStyle

func SetLoggerStyle(loggerStyle string)

SetLoggerStyle sets the logger style based on the provided string.

SetLoggerStyle configures the LoggerStyle environment variable. If the provided style is "default", it sets the style to "default"; otherwise, it defaults to "default" regardless of the input value.

Parameters:

  • loggerStyle: The desired logger style ("default" or any other value defaults to "default")

Example:

SetLoggerStyle("default")
SetLoggerStyle("custom") // Also sets to "default"

func SetTrustedCertificate

func SetTrustedCertificate(cert string)

SetTrustedCertificate sets the trusted certificate for verification.

SetTrustedCertificate stores the provided certificate string in the global trustedCert variable. This certificate can be used for custom certificate validation scenarios.

Parameters:

  • cert: The certificate string to be stored as trusted

Example:

cert := "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"
SetTrustedCertificate(cert)

func StrToLogLevel

func StrToLogLevel(logLevelStr string) int

StrToLogLevel converts a string representation of a log level to its integer value.

This function parses string log level names (case-insensitive) and returns the corresponding integer constant. Supported values are DEBUG, INFO, WARNING, ERROR, and CRITICAL. Any unrecognized value defaults to Critical.

Parameters:

  • logLevelStr: String representation of the log level (e.g., "DEBUG", "info", "Warning")

Returns the integer constant corresponding to the log level, or Critical (0) for unrecognized input.

Example:

level := StrToLogLevel("DEBUG")    // Returns 4
level := StrToLogLevel("invalid")  // Returns 0 (Critical)

func TrustedCertificate

func TrustedCertificate() string

TrustedCertificate returns the trusted certificate for verification.

TrustedCertificate retrieves the currently stored trusted certificate string that was previously set using SetTrustedCertificate. Returns an empty string if no certificate has been set.

Returns the trusted certificate string, or empty string if none is set.

Example:

cert := TrustedCertificate()
if cert != "" {
    // Use the trusted certificate for validation
}

func UnmarshalCookies

func UnmarshalCookies(cookies []byte, cookieJar *cookiejar.Jar) error

UnmarshalCookies deserializes a JSON byte array into a cookie jar.

This function takes a JSON byte array (typically created by MarshalCookies) and populates the provided cookie jar with the deserialized cookies. The cookies are organized by URL and properly set in the jar for use in subsequent HTTP requests.

Parameters:

  • cookies: JSON byte array containing serialized cookie data
  • cookieJar: The cookie jar to populate with deserialized cookies

Returns an error if JSON unmarshaling fails or if URL parsing encounters invalid cookie data.

Example:

err := UnmarshalCookies(savedCookieData, client.GetCookieJar())
if err != nil {
    // handle error
}
// Cookie jar now contains restored cookies

func UserAgent added in v1.4.1

func UserAgent() string

UserAgent returns the user agent string for the Ark SDK in Golang.

UserAgent generates a composite user agent string by combining a Chrome browser user agent (obtained from the fake-useragent library) with the current ARK SDK version. This provides proper identification for HTTP requests made by the SDK while maintaining compatibility with web services that expect browser-like user agents.

Returns a formatted user agent string in the format: "{Chrome User Agent} Ark-SDK-Golang/{version}"

Example:

userAgent := UserAgent()
// userAgent might be:
// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Ark-SDK-Golang/1.2.3"

Types

type ArkBasicAuthTransport added in v1.5.0

type ArkBasicAuthTransport struct {
	// Transport is the underlying http.RoundTripper to wrap
	Transport http.RoundTripper
	// Username is the username for Basic Authentication
	Username string
	// Password is the password for Basic Authentication
	Password string
}

ArkBasicAuthTransport is a custom HTTP transport that adds Basic Authentication to requests.

ArkBasicAuthTransport wraps an existing http.RoundTripper and automatically adds HTTP Basic Authentication headers to every HTTP request using the provided username and password credentials. This is useful for APIs that require Basic Authentication for all requests.

The transport preserves the behavior of the underlying transport while ensuring that the Authorization header is set with properly encoded Basic Authentication credentials on outgoing requests.

Example:

transport := &ArkBasicAuthTransport{
    Transport: http.DefaultTransport,
    Username: "myuser",
    Password: "mypassword",
}

func (*ArkBasicAuthTransport) RoundTrip added in v1.5.0

func (t *ArkBasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements the http.RoundTripper interface and adds Basic Authentication to the request.

RoundTrip sets the Authorization header on the provided request using HTTP Basic Authentication with the configured username and password. The credentials are automatically encoded using base64 as required by the HTTP Basic Authentication standard. After setting the authentication header, it delegates to the underlying Transport's RoundTrip method to perform the actual HTTP request.

Parameters:

  • req: The HTTP request to modify and execute

Returns the HTTP response from the underlying transport and any error encountered.

Example:

transport := &ArkBasicAuthTransport{
    Transport: http.DefaultTransport,
    Username: "myuser",
    Password: "mypassword",
}
resp, err := transport.RoundTrip(req)

type ArkClient

type ArkClient struct {
	BaseURL string
	// contains filtered or unexported fields
}

ArkClient provides a comprehensive HTTP client for interacting with Ark services.

ArkClient wraps the standard Go HTTP client with additional features specifically designed for Ark service interactions. It handles authentication, cookie management, request logging, and automatic token refresh capabilities.

Key features: - Token-based and basic authentication support - Persistent cookie storage with JSON serialization - Automatic retry with token refresh on 401 responses - Configurable headers for all requests - Request/response logging with timing information - TLS configuration support

The client maintains state including authentication tokens, custom headers, and cookie storage, making it suitable for session-based interactions with Ark services.

func NewArkClient

func NewArkClient(baseURL string, token string, tokenType string, authHeaderName string, cookieJar *cookiejar.Jar, refreshCallback func(*ArkClient) error) *ArkClient

NewArkClient creates a new ArkClient instance with comprehensive configuration options.

This is the primary constructor for ArkClient, allowing full customization of authentication, cookie management, and refresh behavior. The client will automatically add HTTPS prefix to the base URL if not present and initialize a new cookie jar if none is provided.

Parameters:

  • baseURL: The base URL for the Ark service
  • token: Authentication token (empty string for no authentication)
  • tokenType: Type of token ("Bearer", "Basic", etc.)
  • authHeaderName: Name of the authorization header (e.g., "Authorization")
  • cookieJar: Cookie jar for session management (nil for new jar)
  • refreshCallback: Function to call for token refresh on 401 responses (nil to disable)

Returns a fully configured ArkClient instance.

Example:

jar, _ := cookiejar.New(nil)
client := NewArkClient(
    "https://api.example.com",
    "abc123",
    "Bearer",
    "Authorization",
    jar,
    func(c *ArkClient) error {
        // Token refresh logic
        return nil
    },
)

func NewSimpleArkClient

func NewSimpleArkClient(baseURL string) *ArkClient

NewSimpleArkClient creates a basic ArkClient instance with minimal configuration.

This is a convenience constructor for creating an ArkClient with only a base URL. It uses default values for all other parameters (no authentication, new cookie jar, no refresh callback). This is suitable for simple use cases or as a starting point for further configuration.

Parameters:

  • baseURL: The base URL for the Ark service (HTTPS prefix will be added if missing)

Returns a configured ArkClient instance ready for basic HTTP operations.

Example:

client := NewSimpleArkClient("api.example.com")
response, err := client.Get(ctx, "/users", nil)

func (*ArkClient) Delete

func (ac *ArkClient) Delete(ctx context.Context, route string, body interface{}) (*http.Response, error)

Delete performs an HTTP DELETE request to the specified route.

This method constructs and executes a DELETE request. An optional body can be provided for DELETE requests that require additional data.

Parameters:

  • ctx: Context for request cancellation and timeout control
  • route: API route/path to append to the base URL
  • body: Optional request body data to be JSON-serialized (can be nil)

Returns the HTTP response or an error if the request fails.

Example:

response, err := client.Delete(ctx, "/users/123", nil)
// Or with body:
deleteOptions := map[string]bool{"force": true}
response, err := client.Delete(ctx, "/users/123", deleteOptions)

func (*ArkClient) DisableRedirections added in v1.5.0

func (ac *ArkClient) DisableRedirections()

DisableRedirections disables automatic HTTP redirection handling.

This method configures the underlying HTTP client to not follow redirects. When disabled, the client will return the first response received, even if it is a redirect (3xx status code). This is useful for scenarios where redirect responses need to be handled manually.

Example:

client.DisableRedirections()
// Now, GET requests will not follow redirects automatically.

func (*ArkClient) EnableRedirections added in v1.5.0

func (ac *ArkClient) EnableRedirections()

EnableRedirections enables automatic HTTP redirection handling.

This method restores the default behavior of the underlying HTTP client, allowing it to automatically follow HTTP redirects (3xx status codes). Use this when you want the client to transparently follow redirects.

Example:

client.EnableRedirections()
// Now, GET requests will follow redirects automatically.

func (*ArkClient) Get

func (ac *ArkClient) Get(ctx context.Context, route string, params map[string]string) (*http.Response, error)

Get performs an HTTP GET request to the specified route.

This method constructs and executes a GET request using the client's base URL, headers, and authentication. Query parameters can be provided via the params map. The method handles automatic token refresh on 401 responses if a refresh callback is configured.

Parameters:

  • ctx: Context for request cancellation and timeout control
  • route: API route/path to append to the base URL
  • params: Query parameters to include in the request (nil for no parameters)

Returns the HTTP response or an error if the request fails.

Example:

params := map[string]string{"limit": "10", "offset": "0"}
response, err := client.Get(ctx, "/users", params)
if err != nil {
    // handle error
}
defer response.Body.Close()

func (*ArkClient) GetCookieJar

func (ac *ArkClient) GetCookieJar() *cookiejar.Jar

GetCookieJar returns the underlying cookie jar instance.

This method provides direct access to the cookiejar.Jar for advanced cookie management operations that are not covered by the convenience methods. Use this when you need full control over cookie behavior.

Returns the cookie jar instance used by this client.

Example:

jar := client.GetCookieJar()
// Perform advanced cookie operations
cookieData, err := MarshalCookies(jar)

func (*ArkClient) GetCookies

func (ac *ArkClient) GetCookies() map[string]string

GetCookies returns a map of all current cookies.

This method extracts all cookies from the cookie jar and returns them as a simple map of names to values. This is useful for inspecting current cookie state or for serialization purposes.

Note: This implementation uses the AllCookies() method from persistent-cookiejar which provides direct access to all stored cookies.

Returns a map containing all current cookie names and values.

Example:

cookies := client.GetCookies()
sessionID := cookies["session_id"]

func (*ArkClient) GetHeaders

func (ac *ArkClient) GetHeaders() map[string]string

GetHeaders returns a copy of the current header map.

This method returns the client's current headers. Note that modifying the returned map will not affect the client's headers - use SetHeader() or UpdateHeaders() to modify headers.

Returns a map containing all current headers.

Example:

currentHeaders := client.GetHeaders()
fmt.Printf("Content-Type: %s\n", currentHeaders["Content-Type"])

func (*ArkClient) GetToken

func (ac *ArkClient) GetToken() string

GetToken returns the current authentication token.

This method returns the raw token string that was set via UpdateToken(). For basic authentication, this will be the base64-encoded credentials.

Returns the current authentication token string.

Example:

currentToken := client.GetToken()
if currentToken == "" {
    // No authentication token is set
}

func (*ArkClient) GetTokenType

func (ac *ArkClient) GetTokenType() string

GetTokenType returns the current token type.

This method returns the token type that was set via UpdateToken(), such as "Bearer", "Basic", "API-Key", etc.

Returns the current token type string.

Example:

tokenType := client.GetTokenType()
fmt.Printf("Using %s authentication\n", tokenType)

func (*ArkClient) Options

func (ac *ArkClient) Options(ctx context.Context, route string) (*http.Response, error)

Options performs an HTTP OPTIONS request to the specified route.

This method constructs and executes an OPTIONS request, typically used to retrieve information about the communication options available for the target resource or server.

Parameters:

  • ctx: Context for request cancellation and timeout control
  • route: API route/path to append to the base URL

Returns the HTTP response or an error if the request fails.

Example:

response, err := client.Options(ctx, "/users")
// Check response headers for allowed methods, CORS info, etc.

func (*ArkClient) Patch

func (ac *ArkClient) Patch(ctx context.Context, route string, body interface{}) (*http.Response, error)

Patch performs an HTTP PATCH request to the specified route.

This method constructs and executes a PATCH request with the provided body serialized as JSON. PATCH requests are typically used for partial updates of existing resources.

Parameters:

  • ctx: Context for request cancellation and timeout control
  • route: API route/path to append to the base URL
  • body: Request body data to be JSON-serialized

Returns the HTTP response or an error if the request fails.

Example:

partialUpdate := map[string]string{"email": "newemail@example.com"}
response, err := client.Patch(ctx, "/users/123", partialUpdate)

func (*ArkClient) Post

func (ac *ArkClient) Post(ctx context.Context, route string, body interface{}) (*http.Response, error)

Post performs an HTTP POST request to the specified route.

This method constructs and executes a POST request with the provided body serialized as JSON. The request includes all configured headers and authentication. Automatic token refresh is handled on 401 responses.

Parameters:

  • ctx: Context for request cancellation and timeout control
  • route: API route/path to append to the base URL
  • body: Request body data to be JSON-serialized

Returns the HTTP response or an error if the request fails.

Example:

userData := map[string]string{"name": "John", "email": "john@example.com"}
response, err := client.Post(ctx, "/users", userData)
if err != nil {
    // handle error
}
defer response.Body.Close()

func (*ArkClient) Put

func (ac *ArkClient) Put(ctx context.Context, route string, body interface{}) (*http.Response, error)

Put performs an HTTP PUT request to the specified route.

This method constructs and executes a PUT request with the provided body serialized as JSON. PUT requests are typically used for updating or replacing existing resources.

Parameters:

  • ctx: Context for request cancellation and timeout control
  • route: API route/path to append to the base URL
  • body: Request body data to be JSON-serialized

Returns the HTTP response or an error if the request fails.

Example:

updatedUser := map[string]string{"name": "John Doe", "email": "john.doe@example.com"}
response, err := client.Put(ctx, "/users/123", updatedUser)

func (*ArkClient) RemoveHeader added in v1.5.0

func (ac *ArkClient) RemoveHeader(key string)

RemoveHeader removes a single HTTP header from the ArkClient.

This method deletes the specified header from the client's header map. The header will no longer be included in subsequent HTTP requests made by this client.

Parameters:

  • key: The header name to remove (e.g., "Authorization", "Content-Type")

Example:

client.RemoveHeader("Authorization")
client.RemoveHeader("X-Custom-Header")

func (*ArkClient) SetCookie

func (ac *ArkClient) SetCookie(key string, value string)

SetCookie sets a single cookie in the client's cookie jar.

This method adds a new cookie to the client's cookie jar, which will be included in subsequent requests to the appropriate domain. The cookie is associated with the client's base URL.

Parameters:

  • key: The cookie name
  • value: The cookie value

Example:

client.SetCookie("session_id", "abc123")
client.SetCookie("user_pref", "dark_mode")

func (*ArkClient) SetCookies

func (ac *ArkClient) SetCookies(cookies map[string]string)

SetCookies replaces all existing cookies with the provided cookie map.

This method removes all existing cookies from the cookie jar and replaces them with the new cookies. Use UpdateCookies() if you want to preserve existing cookies while adding new ones.

Parameters:

  • cookies: Map of cookie names to values that will replace all existing cookies

Example:

cookies := map[string]string{
    "session_id": "abc123",
    "csrf_token": "xyz789",
}
client.SetCookies(cookies)

func (*ArkClient) SetHeader

func (ac *ArkClient) SetHeader(key string, value string)

SetHeader sets a single HTTP header for the ArkClient.

This method adds or updates a single header in the client's header map. The header will be included in all subsequent HTTP requests made by this client. If a header with the same key already exists, it will be overwritten.

Parameters:

  • key: The header name (e.g., "Content-Type", "Accept")
  • value: The header value (e.g., "application/json", "text/plain")

Example:

client.SetHeader("Content-Type", "application/json")
client.SetHeader("Accept", "application/json")

func (*ArkClient) SetHeaders

func (ac *ArkClient) SetHeaders(headers map[string]string)

SetHeaders replaces all existing headers with the provided header map.

This method completely replaces the client's header map with the new headers. Any previously set headers will be lost. Use UpdateHeaders() if you want to preserve existing headers while adding new ones.

Parameters:

  • headers: Map of header names to values that will replace all existing headers

Example:

headers := map[string]string{
    "Content-Type": "application/json",
    "Accept": "application/json",
}
client.SetHeaders(headers)

func (*ArkClient) UpdateCookies

func (ac *ArkClient) UpdateCookies(cookies map[string]string)

UpdateCookies adds or updates cookies in the existing cookie jar.

This method adds new cookies or updates existing ones while preserving cookies that are not specified in the input map.

Parameters:

  • cookies: Map of cookie names to values to add or update

Example:

newCookies := map[string]string{
    "new_session": "def456",
    "updated_pref": "light_mode",
}
client.UpdateCookies(newCookies)

func (*ArkClient) UpdateHeaders

func (ac *ArkClient) UpdateHeaders(headers map[string]string)

UpdateHeaders merges the provided headers into the existing header map.

This method adds new headers or updates existing ones while preserving headers that are not specified in the input map. If a header key already exists, its value will be overwritten.

Parameters:

  • headers: Map of header names to values to add or update

Example:

newHeaders := map[string]string{
    "X-Custom-Header": "custom-value",
    "Authorization": "Bearer new-token",
}
client.UpdateHeaders(newHeaders)

func (*ArkClient) UpdateToken

func (ac *ArkClient) UpdateToken(token string, tokenType string)

UpdateToken updates the authentication token and token type for the client.

This method updates the client's authentication credentials and automatically configures the appropriate authorization header. It supports both standard token-based authentication and basic authentication. For basic auth, the token should be a base64-encoded "username:password" string.

Parameters:

  • token: The authentication token or base64-encoded credentials
  • tokenType: The type of token ("Bearer", "Basic", "API-Key", etc.)

The method will automatically set the Authorization header based on the token type: - For "Basic" type: Decodes the token and sets "Authorization: Basic <credentials>" - For other types: Sets the configured auth header with format "<tokenType> <token>"

Example:

// Bearer token
client.UpdateToken("abc123xyz", "Bearer")

// Basic auth (token should be base64 encoded "user:pass")
client.UpdateToken("dXNlcjpwYXNz", "Basic")

// API key
client.UpdateToken("api-key-value", "API-Key")

type ArkHeaderTransport added in v1.5.0

type ArkHeaderTransport struct {
	// Transport is the underlying http.RoundTripper to wrap
	Transport http.RoundTripper
	// Headers is a map of header names to values that will be added to every request
	Headers map[string]string
}

ArkHeaderTransport is a custom HTTP transport that adds headers to requests.

ArkHeaderTransport wraps an existing http.RoundTripper and automatically adds specified headers to every HTTP request. This is useful for adding common headers like User-Agent, Content-Type, or custom API headers to all requests made through the transport.

The transport preserves the behavior of the underlying transport while ensuring that all specified headers are set on outgoing requests. If a header already exists in the request, it will be overwritten with the value from the Headers map.

Example:

transport := &ArkHeaderTransport{
    Transport: http.DefaultTransport,
    Headers: map[string]string{
        "User-Agent": "MyApp/1.0",
        "X-API-Key": "secret-key",
    },
}

func (*ArkHeaderTransport) RoundTrip added in v1.5.0

func (t *ArkHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements the http.RoundTripper interface and adds headers to the request.

RoundTrip iterates through all headers in the Headers map and sets them on the provided request using req.Header.Set(). This overwrites any existing headers with the same name. After setting all headers, it delegates to the underlying Transport's RoundTrip method to perform the actual HTTP request.

Parameters:

  • req: The HTTP request to modify and execute

Returns the HTTP response from the underlying transport and any error encountered.

Example:

transport := &ArkHeaderTransport{
    Transport: http.DefaultTransport,
    Headers: map[string]string{"User-Agent": "MyApp/1.0"},
}
resp, err := transport.RoundTrip(req)

type ArkLogger

type ArkLogger struct {
	*log.Logger
	// contains filtered or unexported fields
}

ArkLogger provides structured logging with configurable levels and output formatting.

ArkLogger wraps the standard log.Logger and adds features like: - Configurable log levels (Debug, Info, Warning, Error, Critical) - Color-coded console output - Environment variable configuration - Verbose mode control

The logger supports both static configuration and dynamic environment-based configuration for flexible deployment scenarios.

func GetLogger

func GetLogger(app string, logLevel int) *ArkLogger

GetLogger creates a new instance of ArkLogger with application-specific configuration.

This is the primary factory function for creating logger instances. It handles environment variable resolution, logger style configuration, and sets up appropriate formatting. If logLevel is -1, the logger will dynamically resolve the log level from the LOG_LEVEL environment variable.

Parameters:

  • app: Application name used as the logger prefix
  • logLevel: Static log level (0-4), or -1 to resolve from environment

Returns a configured ArkLogger instance, or nil if an unsupported logger style is specified in the LOGGER_STYLE environment variable.

Example:

logger := GetLogger("myapp", Info)        // Static Info level
envLogger := GetLogger("myapp", -1)       // Dynamic level from env

func NewArkLogger

func NewArkLogger(name string, level int, verbose bool, resolveLogLevelFromEnv bool) *ArkLogger

NewArkLogger creates a new instance of ArkLogger with the specified configuration.

This function initializes a new logger with the provided settings. The logger will output to stdout with timestamp formatting and can be configured for different verbosity levels and environment-based configuration.

Parameters:

  • name: The name/prefix for log messages
  • level: The minimum log level (0=Critical, 1=Error, 2=Warning, 3=Info, 4=Debug)
  • verbose: Whether to enable verbose output (false disables all logging)
  • resolveLogLevelFromEnv: Whether to dynamically resolve log level from LOG_LEVEL env var

Returns a configured ArkLogger instance ready for use.

Example:

logger := NewArkLogger("myapp", Info, true, false)
logger.Info("Application started")

func (*ArkLogger) Debug

func (l *ArkLogger) Debug(msg string, v ...interface{})

Debug logs a debug message with green color formatting.

Debug messages are only output when the logger is in verbose mode and the current log level is set to Debug (4) or higher. Debug messages are typically used for detailed diagnostic information.

Parameters:

  • msg: Format string for the log message
  • v: Optional format arguments for the message string

Example:

logger.Debug("Processing user %s with ID %d", username, userID)

func (*ArkLogger) Error

func (l *ArkLogger) Error(msg string, v ...interface{})

Error logs an error message with red color formatting.

Error messages are output when the logger is in verbose mode and the current log level is set to Error (1) or higher. Error messages indicate error conditions that should be investigated.

Parameters:

  • msg: Format string for the log message
  • v: Optional format arguments for the message string

Example:

logger.Error("Failed to connect to database: %v", err)

func (*ArkLogger) Fatal

func (l *ArkLogger) Fatal(msg string, v ...interface{})

Fatal logs a fatal error message with bright red color formatting and exits the program.

Fatal messages are output when the logger is in verbose mode and the current log level is set to Critical (0) or higher. After logging the message, this method calls os.Exit(-1) to terminate the program. This should only be used for unrecoverable error conditions.

Parameters:

  • msg: Format string for the log message
  • v: Optional format arguments for the message string

Example:

logger.Fatal("Cannot start application: %v", err)
// Program terminates after this call

func (*ArkLogger) Info

func (l *ArkLogger) Info(msg string, v ...interface{})

Info logs an informational message with green color formatting.

Info messages are output when the logger is in verbose mode and the current log level is set to Info (3) or higher. Info messages are used for general application flow information.

Parameters:

  • msg: Format string for the log message
  • v: Optional format arguments for the message string

Example:

logger.Info("User %s logged in successfully", username)

func (*ArkLogger) LogLevel

func (l *ArkLogger) LogLevel() int

LogLevel returns the current effective log level of the logger.

This method returns the log level that will be used for filtering log messages. If the logger is configured to resolve the level from environment variables, it will dynamically read the LOG_LEVEL environment variable. Otherwise, it returns the static log level set during logger creation.

Returns the current log level as an integer (0=Critical, 1=Error, 2=Warning, 3=Info, 4=Debug).

func (*ArkLogger) SetVerbose

func (l *ArkLogger) SetVerbose(value bool)

SetVerbose sets the verbosity mode of the logger.

When verbose is false, the logger will not output any messages regardless of the log level. This provides a master switch to disable all logging output from the logger instance.

Parameters:

  • value: true to enable verbose output, false to disable all output

func (*ArkLogger) Warning

func (l *ArkLogger) Warning(msg string, v ...interface{})

Warning logs a warning message with yellow color formatting.

Warning messages are output when the logger is in verbose mode and the current log level is set to Warning (2) or higher. Warning messages indicate potentially problematic situations that don't prevent operation.

Parameters:

  • msg: Format string for the log message
  • v: Optional format arguments for the message string

Example:

logger.Warning("Rate limit approaching for user %s", username)

type ArkPage

type ArkPage[T any] struct {
	Items []*T `json:"items" mapstructure:"items"`
}

ArkPage represents a generic paginated response container from the Ark service.

ArkPage is a type-safe generic structure that wraps paginated API responses. It provides a consistent interface for handling collections of items returned from Ark service endpoints. The generic type parameter T allows for strongly typed access to the contained items while maintaining flexibility across different data types.

The structure supports JSON unmarshaling and mapstructure decoding, making it suitable for use with various serialization libraries and configuration management tools.

Type Parameters:

  • T: The type of items contained in the paginated response

Fields:

  • Items: Slice of pointers to items of type T, representing the paginated data

Example:

// For a paginated response of user objects
type User struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

var userPage ArkPage[User]
err := json.Unmarshal(responseData, &userPage)
if err != nil {
    // handle error
}

for _, user := range userPage.Items {
    fmt.Printf("User: %s (ID: %s)\n", user.Name, user.ID)
}

Directories

Path Synopsis
Package args provides command-line argument handling utilities for the ARK SDK.
Package args provides command-line argument handling utilities for the ARK SDK.
ssh
Package ssh provides Secure Shell (SSH) connection capabilities for the ARK SDK Golang.
Package ssh provides Secure Shell (SSH) connection capabilities for the ARK SDK Golang.
winrm
Package winrm provides Windows Remote Management (WinRM) connection capabilities for the ARK SDK Golang.
Package winrm provides Windows Remote Management (WinRM) connection capabilities for the ARK SDK Golang.
Package isp provides ISP (Identity Service Provider) client functionality for the ARK SDK.
Package isp provides ISP (Identity Service Provider) client functionality for the ARK SDK.
Package keyring provides keyring utilities for the ARK SDK.
Package keyring provides keyring utilities for the ARK SDK.

Jump to

Keyboard shortcuts

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