Documentation
¶
Overview ¶
Package igsdk provides a Go SDK for the Itential Automation Platform and Automation Gateway APIs.
Overview ¶
The igsdk package offers idiomatic Go clients for interacting with Itential's automation infrastructure. It provides HTTP clients with automatic authentication, structured logging, sensitive data redaction, and comprehensive error handling.
Quick Start ¶
Create a Platform client:
import "github.com/itential/igsdk"
client, err := igsdk.NewPlatformClient("api.example.com",
igsdk.WithBasicAuth("admin", "password"),
igsdk.WithTLS(true),
)
if err != nil {
log.Fatal(err)
}
resp, err := client.Get(context.Background(), "/health", nil)
if err != nil {
log.Fatal(err)
}
var result map[string]any
if err := resp.JSON(&result); err != nil {
log.Fatal(err)
}
Create a Gateway client:
gateway, err := igsdk.NewGatewayClient("gateway.example.com",
igsdk.WithBasicAuth("admin@itential", "password"),
)
if err != nil {
log.Fatal(err)
}
devices, err := gateway.Get(context.Background(), "/devices", nil)
Authentication ¶
The SDK supports two authentication methods:
Basic Authentication (default):
client, err := igsdk.NewPlatformClient("api.example.com",
igsdk.WithBasicAuth("username", "password"),
)
OAuth 2.0 Client Credentials (Platform only):
client, err := igsdk.NewPlatformClient("api.example.com",
igsdk.WithOAuth("client-id", "client-secret"),
)
Authentication tokens are automatically managed with optional TTL-based re-authentication:
client, err := igsdk.NewPlatformClient("api.example.com",
igsdk.WithBasicAuth("admin", "password"),
igsdk.WithTTL(30*time.Minute), // Re-authenticate after 30 minutes
)
HTTP Methods ¶
All clients provide standard HTTP methods:
// GET request
resp, err := client.Get(ctx, "/adapters", params)
// POST request with JSON body
payload := map[string]string{"name": "myAdapter"}
resp, err := client.Post(ctx, "/adapters", nil, payload)
// PUT, PATCH, DELETE
resp, err := client.Put(ctx, "/adapters/id", nil, payload)
resp, err := client.Patch(ctx, "/adapters/id", nil, payload)
resp, err := client.Delete(ctx, "/adapters/id", nil)
Query Parameters ¶
Use url.Values for type-safe query parameters:
import "net/url"
params := url.Values{
"limit": []string{"10"},
"offset": []string{"0"},
"filter": []string{"name=test"},
}
resp, err := client.Get(ctx, "/adapters", params)
Response Handling ¶
The Response type provides convenient methods for handling responses:
resp, err := client.Get(ctx, "/health", nil)
if err != nil {
log.Fatal(err)
}
// Check status
if resp.IsSuccess() {
fmt.Println("Success!")
}
// Parse JSON into a struct
var health HealthStatus
if err := resp.JSON(&health); err != nil {
log.Fatal(err)
}
// Access raw body
fmt.Println(resp.Text())
// Check status code
fmt.Println(resp.StatusCode())
Error Handling ¶
HTTP methods return errors only for transport-level failures (network errors, serialization failures, authentication failures). HTTP 4xx and 5xx status codes are returned as responses, not errors — use IsError, CheckStatus, or StatusCode to inspect them.
resp, err := client.Get(ctx, "/resource", nil)
if err != nil {
// Transport or auth error (network failure, bad credentials, etc.)
return err
}
if resp.IsError() {
// HTTP 4xx or 5xx — inspect and handle
fmt.Printf("HTTP error: %d\n", resp.StatusCode())
var body map[string]any
_ = resp.JSON(&body)
return fmt.Errorf("request failed: %d", resp.StatusCode())
}
To use Go's errors.As for status code handling, call CheckStatus explicitly:
if err := resp.CheckStatus(); err != nil {
var httpErr *igsdk.HTTPStatusError
if errors.As(err, &httpErr) {
fmt.Printf("HTTP error: %d\n", httpErr.StatusCode)
}
}
Authentication errors (wrong credentials, OAuth failure) are always returned as errors regardless of this behavior:
Structured Logging ¶
The SDK uses Go's standard log/slog package for structured logging. At Debug level, every request logs method, URL, headers, body, status code, and round-trip duration. Sensitive values are redacted before they reach the log output.
import "log/slog"
logger := igsdk.NewJSONLogger(
igsdk.WithLogOutput(os.Stdout),
igsdk.WithLogLevel(slog.LevelDebug),
)
client, err := igsdk.NewPlatformClient("api.example.com",
igsdk.WithLogger(logger),
)
For sensitive data redaction, attach a Scanner to the logger:
scanner := igsdk.NewScanner() logger := igsdk.NewLogger( igsdk.WithLogOutput(os.Stdout), igsdk.WithSensitiveDataRedaction(scanner), )
For request tracing and correlation IDs, use LogContext to attach fields to the context. The SDK includes these fields in every log entry for that request:
ctx = igsdk.LogContext(ctx, "request_id", reqID, "tenant", tenantID) resp, err := client.Get(ctx, "/adapters", nil) // Debug log entries for this request include request_id and tenant.
Configuration Options ¶
Clients support extensive configuration via functional options:
client, err := igsdk.NewPlatformClient("api.example.com",
igsdk.WithPort(8443),
igsdk.WithTLS(true),
igsdk.WithVerify(false), // Disable cert verification
igsdk.WithTimeout(60*time.Second), // Request timeout
igsdk.WithTTL(30*time.Minute), // Auth token TTL
igsdk.WithBasicAuth("admin", "password"),
igsdk.WithHTTPClient(customClient), // Custom http.Client
igsdk.WithLogger(logger), // Custom logger
igsdk.WithScanner(scanner), // Custom scanner
)
Version Information ¶
Access SDK version and build metadata:
info := igsdk.GetInfo()
fmt.Println(info.FullVersion()) // "igsdk v1.0.0 (abc123)"
if info.IsRelease() {
fmt.Printf("Version: %s\n", info.Version)
fmt.Printf("Build: %s\n", info.Build)
}
Context Support ¶
All HTTP methods accept a context for cancellation and timeouts:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := client.Get(ctx, "/slow-endpoint", nil)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("Request timed out")
}
return err
}
Sensitive Data Redaction ¶
The Scanner type automatically redacts sensitive data from logs:
scanner := igsdk.NewScanner()
// Built-in patterns detect:
// - Passwords, API keys, tokens
// - Secrets, bearer tokens
// - URLs with credentials
// - Email addresses in auth contexts
// Add custom patterns
scanner.AddPattern("custom_token", `token=[a-zA-Z0-9]+`)
// Use with logger
logger := igsdk.NewLogger(
igsdk.WithSensitiveDataRedaction(scanner),
)
Platform vs Gateway ¶
Platform Client:
- Connects to Itential Automation Platform
- Supports OAuth 2.0 and Basic Auth
- Base path: / (root)
- Default user: "admin"
Gateway Client:
- Connects to Itential Automation Gateway
- Supports Basic Auth only
- Base path: /api/v2.0
- Default user: "admin@itential"
Best Practices ¶
1. Always use context for cancellation and timeouts 2. Check response status before parsing JSON 3. Use url.Values for query parameters (type-safe) 4. Enable structured logging in production 5. Use sensitive data redaction for security 6. Set appropriate timeouts for your use case 7. Handle HTTPStatusError explicitly for better error messages 8. Reuse clients - they are safe for concurrent use
Thread Safety ¶
All client types are safe for concurrent use. You can share a single client across multiple goroutines:
client, _ := igsdk.NewPlatformClient("api.example.com")
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
client.Get(context.Background(), "/health", nil)
}()
}
wg.Wait()
Index ¶
- Constants
- Variables
- func LogContext(ctx context.Context, keyvals ...any) context.Context
- func NewDiscardLogger() *slog.Logger
- func NewJSONLogger(opts ...LoggerOption) *slog.Logger
- func NewLogger(opts ...LoggerOption) *slog.Logger
- type ClientOption
- func WithBasicAuth(user, password string) ClientOption
- func WithHTTPClient(client *http.Client) ClientOption
- func WithLogger(logger *slog.Logger) ClientOption
- func WithOAuth(clientID, clientSecret string) ClientOption
- func WithPort(port int) ClientOption
- func WithScanner(scanner *Scanner) ClientOption
- func WithTLS(enabled bool) ClientOption
- func WithTTL(ttl time.Duration) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- func WithVerify(enabled bool) ClientOption
- type GatewayClient
- func (c *GatewayClient) BaseURL() string
- func (c *GatewayClient) Delete(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
- func (c *GatewayClient) Get(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
- func (c *GatewayClient) Patch(ctx context.Context, path string, params url.Values, payload any, ...) (*Response, error)
- func (c *GatewayClient) Post(ctx context.Context, path string, params url.Values, payload any, ...) (*Response, error)
- func (c *GatewayClient) Put(ctx context.Context, path string, params url.Values, payload any, ...) (*Response, error)
- type HTTPStatusError
- type Info
- type LoggerOption
- type PlatformClient
- func (c *PlatformClient) BaseURL() string
- func (c *PlatformClient) Delete(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
- func (c *PlatformClient) Get(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
- func (c *PlatformClient) Patch(ctx context.Context, path string, params url.Values, payload any, ...) (*Response, error)
- func (c *PlatformClient) Post(ctx context.Context, path string, params url.Values, payload any, ...) (*Response, error)
- func (c *PlatformClient) Put(ctx context.Context, path string, params url.Values, payload any, ...) (*Response, error)
- type RequestOption
- type Response
- type Scanner
Constants ¶
const ( // Name is the SDK name. Name = "igsdk" // Author is the SDK author/maintainer. Author = "Itential" )
Variables ¶
var Build string
Build represents the Git SHA (short form) that the SDK was compiled from. This value is set at build time using linker flags:
-ldflags "-X github.com/itential/igsdk.Build=<commit-sha>"
var Version = ""
Version represents the semantic version of the SDK. This value is set at build time using linker flags:
-ldflags "-X github.com/itential/igsdk.Version=<version>"
Functions ¶
func LogContext ¶
LogContext attaches key-value pairs to the context for request tracing. The SDK automatically includes these values in all log entries generated during requests made with this context, enabling correlation across calls.
Keys must be strings; non-string keys are silently skipped. If an odd number of arguments is provided the last one is dropped.
Example:
ctx = igsdk.LogContext(ctx, "request_id", reqID, "tenant", tenantID) resp, err := client.Get(ctx, "/resources", nil) // SDK debug logs for this request will include request_id and tenant fields.
func NewDiscardLogger ¶
NewDiscardLogger creates a logger that discards all output. Useful for testing or when logging should be explicitly disabled.
func NewJSONLogger ¶
func NewJSONLogger(opts ...LoggerOption) *slog.Logger
NewJSONLogger creates a new structured logger with JSON output. Defaults to writing to os.Stderr at Info level. Use WithLogOutput to redirect output.
func NewLogger ¶
func NewLogger(opts ...LoggerOption) *slog.Logger
NewLogger creates a new structured logger with text output. Defaults to writing to os.Stderr at Info level. Use WithLogOutput to redirect output. For JSON output use NewJSONLogger. For no output use NewDiscardLogger.
Types ¶
type ClientOption ¶
type ClientOption func(*clientConfig)
ClientOption is a functional option for configuring Platform and Gateway clients. Options can be passed to NewPlatformClient or NewGatewayClient to customize the client's behavior, authentication, timeouts, and logging.
func WithBasicAuth ¶
func WithBasicAuth(user, password string) ClientOption
WithBasicAuth sets basic authentication credentials.
func WithHTTPClient ¶
func WithHTTPClient(client *http.Client) ClientOption
WithHTTPClient sets a custom HTTP client.
func WithLogger ¶
func WithLogger(logger *slog.Logger) ClientOption
WithLogger sets a custom structured logger for the client. The logger should be created with NewLogger or NewJSONLogger.
func WithOAuth ¶
func WithOAuth(clientID, clientSecret string) ClientOption
WithOAuth sets OAuth client credentials.
func WithScanner ¶
func WithScanner(scanner *Scanner) ClientOption
WithScanner sets a custom sensitive data scanner for the client.
func WithTLS ¶
func WithTLS(enabled bool) ClientOption
WithTLS enables or disables TLS for the client.
func WithTTL ¶
func WithTTL(ttl time.Duration) ClientOption
WithTTL sets the authentication token TTL.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) ClientOption
WithTimeout sets the HTTP client timeout.
func WithVerify ¶
func WithVerify(enabled bool) ClientOption
WithVerify enables or disables TLS certificate verification.
type GatewayClient ¶
type GatewayClient struct {
// contains filtered or unexported fields
}
GatewayClient provides HTTP API access to the Itential Automation Gateway.
GatewayClient is safe for concurrent use by multiple goroutines. All methods accept a context.Context for cancellation and timeout control.
The Gateway client automatically prepends /api/v2.0 to all request paths. Supported HTTP methods: Get, Post, Put, Patch, Delete
Authentication is handled automatically using Basic Auth. OAuth is not supported for Gateway clients.
func NewGatewayClient ¶
func NewGatewayClient(host string, opts ...ClientOption) (*GatewayClient, error)
NewGatewayClient creates a new client for the Itential Automation Gateway.
The host parameter specifies the Gateway hostname (without protocol or path). The Gateway client automatically uses the /api/v2.0 base path.
Default configuration:
- Port: 443 (HTTPS) or 80 (HTTP)
- TLS: Enabled
- Certificate verification: Enabled
- Timeout: 30 seconds
- Base path: /api/v2.0
- Authentication: Basic auth (username: "admin@itential", password: "admin")
Returns an error if OAuth credentials are provided (not supported for Gateway), or if the username or password is empty.
Example:
client, err := igsdk.NewGatewayClient("gateway.example.com",
igsdk.WithBasicAuth("admin@itential", "password"),
)
func (*GatewayClient) BaseURL ¶
func (c *GatewayClient) BaseURL() string
BaseURL returns the base URL used by the client, including the /api/v2.0 path.
Example return value: "https://gateway.example.com/api/v2.0"
func (*GatewayClient) Delete ¶
func (c *GatewayClient) Delete(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
Delete performs an HTTP DELETE request to the specified path.
The path is automatically prefixed with /api/v2.0 for Gateway requests.
Example:
resp, err := client.Delete(ctx, "/devices/dev123", nil)
func (*GatewayClient) Get ¶
func (c *GatewayClient) Get(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
Get performs an HTTP GET request to the specified path.
The path is automatically prefixed with /api/v2.0 for Gateway requests. Optional query parameters can be provided via params (use nil for no parameters).
Example:
resp, err := client.Get(ctx, "/devices", nil) // Actual request: GET /api/v2.0/devices
func (*GatewayClient) Patch ¶
func (c *GatewayClient) Patch(ctx context.Context, path string, params url.Values, payload any, opts ...RequestOption) (*Response, error)
Patch performs an HTTP PATCH request to the specified path with a JSON payload.
The path is automatically prefixed with /api/v2.0 for Gateway requests.
func (*GatewayClient) Post ¶
func (c *GatewayClient) Post(ctx context.Context, path string, params url.Values, payload any, opts ...RequestOption) (*Response, error)
Post performs an HTTP POST request to the specified path with a JSON payload.
The path is automatically prefixed with /api/v2.0 for Gateway requests. The payload is automatically marshaled to JSON.
Example:
device := map[string]any{"name": "Router1", "ip": "10.0.0.1"}
resp, err := client.Post(ctx, "/devices", nil, device)
func (*GatewayClient) Put ¶
func (c *GatewayClient) Put(ctx context.Context, path string, params url.Values, payload any, opts ...RequestOption) (*Response, error)
Put performs an HTTP PUT request to the specified path with a JSON payload.
The path is automatically prefixed with /api/v2.0 for Gateway requests.
type HTTPStatusError ¶
type HTTPStatusError struct {
// StatusCode is the HTTP status code (e.g., 404, 500).
StatusCode int
// Status is the HTTP status text (e.g., "404 Not Found").
Status string
// Response contains the full HTTP response including body.
// Useful for extracting error details from the response body.
Response *Response
}
HTTPStatusError is returned when an HTTP request results in a 4xx or 5xx status code.
This error type allows callers to inspect the status code, status text, and full response body to determine the appropriate action.
Example:
resp, err := client.Get(ctx, "/resource", nil)
if err != nil {
var httpErr *igsdk.HTTPStatusError
if errors.As(err, &httpErr) {
switch httpErr.StatusCode {
case 404:
fmt.Println("Resource not found")
case 401:
fmt.Println("Authentication failed")
default:
fmt.Printf("HTTP error: %d\n", httpErr.StatusCode)
}
}
return err
}
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
type Info ¶
type Info struct {
// Name is the SDK name (always "igsdk").
Name string
// Author is the SDK author/maintainer (always "Itential").
Author string
// Version is the semantic version string (e.g., "v1.2.3").
// Empty string indicates a development build.
Version string
// Build is the Git commit SHA (short form) the SDK was built from.
// Empty string indicates version information is not available.
Build string
}
Info contains SDK metadata including name, version, author, and build information. Use GetInfo() to obtain an Info instance populated with current build metadata.
func GetInfo ¶
func GetInfo() Info
GetInfo returns SDK information including name, version, author, and build details. The returned Info is populated with values from the Build and Version package variables, which are typically set at compile time via linker flags.
func (Info) FullVersion ¶
FullVersion returns a complete version string including build information. Format: "igsdk v1.2.3 (abc123)" for release builds. Format: "igsdk development" for development builds.
func (Info) IsRelease ¶
IsRelease returns true if the SDK is a release build. A release build is one where both Version and Build are set (non-empty). Returns false for development builds where version information is not available.
func (Info) ShortVersion ¶
ShortVersion returns just the version string without build information. Returns "devel" if version is not set.
type LoggerOption ¶
type LoggerOption func(*loggerConfig)
LoggerOption configures a logger instance.
func WithLogLevel ¶
func WithLogLevel(level slog.Level) LoggerOption
WithLogLevel sets the minimum log level.
func WithLogOutput ¶
func WithLogOutput(w io.Writer) LoggerOption
WithLogOutput sets the log output writer.
func WithLogSource ¶
func WithLogSource(enabled bool) LoggerOption
WithLogSource enables source code location in log messages.
func WithReplaceAttr ¶
WithReplaceAttr sets a custom attribute replacer for the logger.
func WithSensitiveDataRedaction ¶
func WithSensitiveDataRedaction(scanner *Scanner) LoggerOption
WithSensitiveDataRedaction enables redaction of sensitive data in log messages.
type PlatformClient ¶
type PlatformClient struct {
// contains filtered or unexported fields
}
PlatformClient provides HTTP API access to the Itential Automation Platform.
PlatformClient is safe for concurrent use by multiple goroutines. All methods accept a context.Context for cancellation and timeout control.
Supported HTTP methods: Get, Post, Put, Patch, Delete
Authentication is handled automatically using either Basic Auth or OAuth 2.0, depending on the options provided to NewPlatformClient.
func NewPlatformClient ¶
func NewPlatformClient(host string, opts ...ClientOption) (*PlatformClient, error)
NewPlatformClient creates a new client for the Itential Automation Platform.
The host parameter specifies the Platform hostname (without protocol or path). Additional configuration can be provided via functional options.
Default configuration:
- Port: 443 (HTTPS) or 80 (HTTP)
- TLS: Enabled
- Certificate verification: Enabled
- Timeout: 30 seconds
- Authentication: Basic auth (username: "admin", password: "admin")
Returns an error if the provided credentials are incomplete:
- OAuth: both client ID and client secret must be set
- Basic auth: both username and password must be set
Example:
client, err := igsdk.NewPlatformClient("api.example.com",
igsdk.WithBasicAuth("admin", "password"),
igsdk.WithTimeout(60*time.Second),
)
func (*PlatformClient) BaseURL ¶
func (c *PlatformClient) BaseURL() string
BaseURL returns the base URL used by the client.
The base URL includes the scheme (http/https), host, and port, but does not include any path components.
Example return value: "https://api.example.com:8443"
func (*PlatformClient) Delete ¶
func (c *PlatformClient) Delete(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
Delete performs an HTTP DELETE request to the specified path.
The path parameter specifies the API endpoint (e.g., "/adapters/123"). Optional query parameters can be provided via params (use nil for no parameters).
Example:
resp, err := client.Delete(ctx, "/adapters/123", nil)
func (*PlatformClient) Get ¶
func (c *PlatformClient) Get(ctx context.Context, path string, params url.Values, opts ...RequestOption) (*Response, error)
Get performs an HTTP GET request to the specified path.
The path parameter specifies the API endpoint (e.g., "/health/server"). Optional query parameters can be provided via params (use nil for no parameters).
The request automatically includes authentication headers and will re-authenticate if the token has expired (when TTL is configured).
Example:
params := url.Values{"limit": []string{"10"}}
resp, err := client.Get(ctx, "/adapters", params)
func (*PlatformClient) Patch ¶
func (c *PlatformClient) Patch(ctx context.Context, path string, params url.Values, payload any, opts ...RequestOption) (*Response, error)
Patch performs an HTTP PATCH request to the specified path with a JSON payload.
The payload is automatically marshaled to JSON and sent with appropriate headers. PATCH typically applies partial modifications to a resource.
Example:
changes := map[string]any{"enabled": false}
resp, err := client.Patch(ctx, "/adapters/123", nil, changes)
func (*PlatformClient) Post ¶
func (c *PlatformClient) Post(ctx context.Context, path string, params url.Values, payload any, opts ...RequestOption) (*Response, error)
Post performs an HTTP POST request to the specified path with a JSON payload.
The payload is automatically marshaled to JSON and sent with appropriate Content-Type and Accept headers.
Example:
payload := map[string]any{"name": "MyAdapter", "type": "HTTP"}
resp, err := client.Post(ctx, "/adapters", nil, payload)
func (*PlatformClient) Put ¶
func (c *PlatformClient) Put(ctx context.Context, path string, params url.Values, payload any, opts ...RequestOption) (*Response, error)
Put performs an HTTP PUT request to the specified path with a JSON payload.
The payload is automatically marshaled to JSON and sent with appropriate headers. PUT typically replaces the entire resource at the specified path.
Example:
updates := map[string]any{"name": "UpdatedName", "enabled": true}
resp, err := client.Put(ctx, "/adapters/123", nil, updates)
type RequestOption ¶
type RequestOption func(*requestConfig)
RequestOption configures a single HTTP request. Options are applied after SDK defaults, so they can override headers like Accept or Content-Type.
func WithHeader ¶
func WithHeader(key, value string) RequestOption
WithHeader sets a custom HTTP header on the request, overriding any SDK default for that header key. Call multiple times to set multiple headers.
Example — request XML instead of JSON:
resp, err := client.Get(ctx, "/report", nil, igsdk.WithHeader("Accept", "application/xml"))
type Response ¶
type Response struct {
// Raw is the underlying http.Response from the HTTP request.
Raw *http.Response
// Body contains the complete response body as bytes.
Body []byte
}
Response wraps an HTTP response with convenience methods for common operations.
Response provides methods to:
- Parse JSON responses into Go types
- Access response body as text
- Check response status (success/error)
- Access headers and status codes
The Response type is returned by all HTTP methods on Platform and Gateway clients.
func NewResponse ¶
NewResponse creates a new Response from an http.Response and body bytes.
func (*Response) CheckStatus ¶
CheckStatus returns an error if the response status indicates failure.
Returns nil for 2xx and 3xx status codes. Returns HTTPStatusError for 4xx and 5xx status codes.
Note: HTTP methods on Platform and Gateway clients automatically call CheckStatus, so you typically don't need to call this manually.
func (*Response) JSON ¶
JSON unmarshals the response body into the provided value.
The value parameter must be a pointer to the target type. JSON uses the standard encoding/json package for unmarshaling.
Example with a struct:
type User struct {
ID string `json:"_id"`
Name string `json:"name"`
}
var user User
if err := resp.JSON(&user); err != nil {
return err
}
Example with a map:
var result map[string]any
if err := resp.JSON(&result); err != nil {
return err
}
func (*Response) StatusCode ¶
StatusCode returns the HTTP status code of the response.
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner detects and redacts sensitive data patterns in text.
Scanner uses regular expressions to identify sensitive information such as:
- Passwords and secrets
- API keys and access tokens
- Bearer tokens
- URLs with embedded credentials
- Email addresses in authentication contexts
Scanners are safe for concurrent use. Custom patterns can be added with AddPattern.
Example:
scanner := igsdk.NewScanner()
scanner.AddPattern("custom_token", `token=[a-zA-Z0-9]+`)
redacted := scanner.ScanAndRedact("password=secret123")
// Returns: "[REDACTED_PASSWORD]"
func NewScanner ¶
func NewScanner() *Scanner
NewScanner creates a new scanner with built-in sensitive data detection patterns.
The default patterns detect:
- API keys (api_key, apikey)
- Bearer tokens
- Access tokens
- Passwords (password, passwd, pwd)
- Secrets (secret, client_secret)
- URLs with credentials (http://user:pass@host)
- Email addresses in auth contexts
Additional patterns can be added with AddPattern.
func (*Scanner) AddPattern ¶
AddPattern adds a new pattern to the scanner.
func (*Scanner) HasSensitiveData ¶
HasSensitiveData checks if text contains any sensitive data patterns.
func (*Scanner) ListPatterns ¶
ListPatterns returns all pattern names in sorted order.
func (*Scanner) RemovePattern ¶
RemovePattern removes a pattern from the scanner.
func (*Scanner) ScanAndRedact ¶
ScanAndRedact scans text for sensitive data patterns and redacts matches.