Documentation
¶
Overview ¶
Package inbio is the official Go SDK for the in.bio URL shortener API.
Two entry points are available:
- The free, keyless shorten endpoint via the package-level Shorten function (no account or token required).
- The authenticated API v1 via NewClient, which exposes the Links, Folders, Tags, Account and Webhooks services.
See https://docs.in.bio for the full API documentation.
Index ¶
- Constants
- func Bool(v bool) *bool
- func Int(v int) *int
- func Int64(v int64) *int64
- func String(v string) *string
- func Time(v time.Time) *time.Time
- type AccessError
- type AccountService
- type Analytics
- type AnalyticsCount
- type AnalyticsOptions
- type AnalyticsPoint
- type AnalyticsRange
- type AnalyticsTotals
- type AuthenticationError
- type BulkCreateFailure
- type BulkCreateResult
- type Client
- type CreateLinkParams
- type EntitlementError
- type Error
- type Event
- type Folder
- type FoldersService
- type Link
- type LinkPage
- type LinksService
- func (s *LinksService) Analytics(ctx context.Context, id int64, opts *AnalyticsOptions) (*Analytics, error)
- func (s *LinksService) BulkCreate(ctx context.Context, links []CreateLinkParams) (*BulkCreateResult, error)
- func (s *LinksService) Create(ctx context.Context, params CreateLinkParams) (*Link, error)
- func (s *LinksService) Delete(ctx context.Context, id int64) error
- func (s *LinksService) Disable(ctx context.Context, id int64) (*Link, error)
- func (s *LinksService) Enable(ctx context.Context, id int64) (*Link, error)
- func (s *LinksService) Get(ctx context.Context, id int64) (*Link, error)
- func (s *LinksService) Iter(ctx context.Context, opts *ListOptions) iter.Seq2[Link, error]
- func (s *LinksService) List(ctx context.Context, opts *ListOptions) (*LinkPage, error)
- func (s *LinksService) QR(ctx context.Context, id int64, opts *QROptions) (*QRCode, error)
- func (s *LinksService) Update(ctx context.Context, id int64, params UpdateLinkParams) (*Link, error)
- type ListOptions
- type Meta
- type NotFoundError
- type Option
- type PageLinks
- type QRCode
- type QROptions
- type RateLimitError
- type ServerError
- type ShortenResult
- type SignatureVerificationError
- type StateConflictError
- type Tag
- type TagsService
- type UTM
- type UpdateLinkParams
- type Usage
- type UsageCounters
- type UsageLimits
- type ValidationError
- type WebhooksService
Constants ¶
const DefaultWebhookTolerance = 300 * time.Second
DefaultWebhookTolerance is the default allowed clock skew between the signature timestamp and now.
const EnvToken = "INBIO_API_TOKEN"
EnvToken is the environment variable consulted for an API token when none is supplied with WithToken.
const Version = "0.1.0"
Version is the version of this SDK.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AccessError ¶
type AccessError struct {
// Required is the missing token scope when Type == "scope",
// e.g. "links:write".
Required string
// contains filtered or unexported fields
}
AccessError is returned for 403 responses. Type on the embedded base error is "plan" (API access not on your plan), "scope" (missing token scope) or "account" (suspended account).
type AccountService ¶
type AccountService struct {
// contains filtered or unexported fields
}
AccountService provides access to the account endpoints. Access it via Client.Account.
type Analytics ¶
type Analytics struct {
Range AnalyticsRange `json:"range"`
Totals AnalyticsTotals `json:"totals"`
Series []AnalyticsPoint `json:"series"`
Countries []AnalyticsCount `json:"countries"`
Devices []AnalyticsCount `json:"devices"`
Browsers []AnalyticsCount `json:"browsers"`
Referrers []AnalyticsCount `json:"referrers"`
}
Analytics is the per-link analytics report. Dates use YYYY-MM-DD.
type AnalyticsCount ¶
AnalyticsCount is a clicks count for a dimension value (country code, device type, browser name or referrer host).
type AnalyticsOptions ¶
type AnalyticsOptions struct {
// From defaults to 30 days before To, clamped to your plan's analytics
// retention.
From string
// To defaults to today.
To string
}
AnalyticsOptions are the options for LinksService.Analytics. Dates use YYYY-MM-DD.
type AnalyticsPoint ¶
type AnalyticsPoint struct {
Date string `json:"date"`
Clicks int64 `json:"clicks"`
Uniques int64 `json:"uniques"`
}
AnalyticsPoint is one day in the analytics time series.
type AnalyticsRange ¶
AnalyticsRange is the reported date range.
type AnalyticsTotals ¶
type AnalyticsTotals struct {
Clicks int64 `json:"clicks"`
Uniques int64 `json:"uniques"`
BotClicks int64 `json:"botClicks"`
}
AnalyticsTotals are the totals for the range. Bot traffic is excluded from all numbers except BotClicks.
type AuthenticationError ¶
type AuthenticationError struct {
// contains filtered or unexported fields
}
AuthenticationError is returned for 401 responses (missing or invalid token).
func (*AuthenticationError) Unwrap ¶
func (e *AuthenticationError) Unwrap() error
Unwrap returns the base *Error.
type BulkCreateFailure ¶
type BulkCreateFailure struct {
// Index is the zero-based index of the failed row in the request.
Index int `json:"index"`
// Error is the failure message.
Error string `json:"error"`
}
BulkCreateFailure describes one failed row of a bulk create.
type BulkCreateResult ¶
type BulkCreateResult struct {
Created []Link `json:"created"`
Failed []BulkCreateFailure `json:"failed"`
}
BulkCreateResult is the outcome of LinksService.BulkCreate. Rows fail independently.
type Client ¶
type Client struct {
// Links provides access to the link endpoints (/api/v1/links).
Links *LinksService
// Folders provides access to the folder endpoints (/api/v1/folders).
Folders *FoldersService
// Tags provides access to the tag endpoints (/api/v1/tags).
Tags *TagsService
// Account provides access to the account endpoints (/api/v1/account).
Account *AccountService
// Webhooks verifies webhook signatures. It performs no HTTP requests.
Webhooks *WebhooksService
// contains filtered or unexported fields
}
Client is an in.bio API client. Construct one with NewClient.
type CreateLinkParams ¶
type CreateLinkParams struct {
// DestinationURL is required: http/https, max 2048 chars.
DestinationURL string `json:"destination_url"`
// Slug is a custom slug, 3-64 chars [a-zA-Z0-9-_]; omitted -> random.
Slug string `json:"slug,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Notes string `json:"notes,omitempty"`
// RedirectType is 301, 302 (default) or 307.
RedirectType int `json:"redirect_type,omitempty"`
FolderID int64 `json:"folder_id,omitempty"`
Tags []string `json:"tags,omitempty"`
// ExpiresAt requires the link expiration feature (Pro+).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
// FallbackURL is shown after expiry (Pro+).
FallbackURL string `json:"fallback_url,omitempty"`
// ClickLimit requires the click limits feature (Pro+).
ClickLimit int `json:"click_limit,omitempty"`
// Password requires the password protection feature (Pro+).
Password string `json:"password,omitempty"`
UTM *UTM `json:"utm,omitempty"`
}
CreateLinkParams are the fields for LinksService.Create and LinksService.BulkCreate. Only DestinationURL is required; zero-valued optional fields are omitted from the request.
type EntitlementError ¶
type EntitlementError struct {
// contains filtered or unexported fields
}
EntitlementError is returned for 422 responses with error.type = "entitlement" (a plan feature or limit was hit, e.g. the monthly link limit).
func (*EntitlementError) Unwrap ¶
func (e *EntitlementError) Unwrap() error
Unwrap returns the base *Error.
type Error ¶
type Error struct {
// StatusCode is the HTTP status code of the response.
StatusCode int
// Type is the API error type when present: "plan", "scope", "account",
// "state" or "entitlement".
Type string
// Message is the human-readable error message.
Message string
// Body is the raw response body, useful for debugging.
Body []byte
}
Error is the base error returned for every non-2xx API response. All typed errors below wrap it, so both of these work:
var apiErr *inbio.Error
if errors.As(err, &apiErr) { ... } // any API error
var notFound *inbio.NotFoundError
if errors.As(err, ¬Found) { ... } // a specific one
type Event ¶
type Event struct {
// ID is the event id, e.g. "evt_01J...".
ID string `json:"id"`
// Event is the event name, e.g. "link.created".
Event string `json:"event"`
// CreatedAt is when the event occurred.
CreatedAt time.Time `json:"created_at"`
// Data is the raw event payload. For link.* events it holds the link
// fields as in the API resource; use [Event.Link] to decode it.
Data json.RawMessage `json:"data"`
}
Event is a parsed webhook event. Event names: link.created, link.updated, link.deleted, link.clicked, link.expired, link.disabled, link.click_limit_reached, subscription.updated.
type Folder ¶
type Folder struct {
ID int64 `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
Position int `json:"position"`
LinksCount int `json:"links_count"`
CreatedAt time.Time `json:"created_at"`
}
Folder is a link folder.
type FoldersService ¶
type FoldersService struct {
// contains filtered or unexported fields
}
FoldersService provides access to the folder endpoints. Access it via Client.Folders.
type Link ¶
type Link struct {
ID int64 `json:"id"`
Slug string `json:"slug"`
ShortURL string `json:"short_url"`
DestinationURL string `json:"destination_url"`
Title *string `json:"title"`
Description *string `json:"description"`
Status string `json:"status"`
RedirectType int `json:"redirect_type"`
FolderID *int64 `json:"folder_id"`
Tags []string `json:"tags"`
ExpiresAt *time.Time `json:"expires_at"`
ClickLimit *int `json:"click_limit"`
HasPassword bool `json:"has_password"`
TotalClicks int64 `json:"total_clicks"`
UniqueClicks int64 `json:"unique_clicks"`
LastClickedAt *time.Time `json:"last_clicked_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Link is a short link resource as returned by the API. Unknown JSON fields returned by newer API versions are ignored.
type LinkPage ¶
type LinkPage struct {
Data []Link `json:"data"`
Links PageLinks `json:"links"`
Meta Meta `json:"meta"`
}
LinkPage is one page of links as returned by LinksService.List.
type LinksService ¶
type LinksService struct {
// contains filtered or unexported fields
}
LinksService provides access to the link endpoints. Access it via Client.Links.
func (*LinksService) Analytics ¶
func (s *LinksService) Analytics(ctx context.Context, id int64, opts *AnalyticsOptions) (*Analytics, error)
Analytics fetches the link's analytics report (GET /links/{id}/analytics, scope analytics:read). A nil opts uses the API defaults (last 30 days).
func (*LinksService) BulkCreate ¶
func (s *LinksService) BulkCreate(ctx context.Context, links []CreateLinkParams) (*BulkCreateResult, error)
BulkCreate creates up to 100 links in one request (POST /links/bulk, scope links:write; requires the bulk actions feature, Business plan). Rows fail independently — inspect the result's Failed slice.
func (*LinksService) Create ¶
func (s *LinksService) Create(ctx context.Context, params CreateLinkParams) (*Link, error)
Create creates a link (POST /links, scope links:write).
func (*LinksService) Delete ¶
func (s *LinksService) Delete(ctx context.Context, id int64) error
Delete soft-deletes a link; it stops redirecting immediately (DELETE /links/{id}, scope links:write).
func (*LinksService) Disable ¶
Disable disables an active link (POST /links/{id}/disable, scope links:write). The link must currently be "active"; any other status returns a StateConflictError.
func (*LinksService) Enable ¶
Enable re-enables a disabled link (POST /links/{id}/enable, scope links:write). The link must currently be "disabled"; any other status returns a StateConflictError.
func (*LinksService) Iter ¶
func (s *LinksService) Iter(ctx context.Context, opts *ListOptions) iter.Seq2[Link, error]
Iter returns an iterator over every link matching opts, fetching pages lazily (auto-pagination). Requires Go 1.23 range-over-func:
for link, err := range client.Links.Iter(ctx, nil) {
if err != nil {
return err
}
fmt.Println(link.ShortURL)
}
Iteration starts at opts.Page (or page 1) and stops at the last page, on the first error, or when the loop breaks.
func (*LinksService) List ¶
func (s *LinksService) List(ctx context.Context, opts *ListOptions) (*LinkPage, error)
List returns one page of links (GET /links, scope links:read).
func (*LinksService) QR ¶
QR fetches the link's QR code image (GET /links/{id}/qr, scope links:read). A nil opts uses the API defaults (PNG).
func (*LinksService) Update ¶
func (s *LinksService) Update(ctx context.Context, id int64, params UpdateLinkParams) (*Link, error)
Update updates any subset of a link's fields (PATCH /links/{id}, scope links:write).
type ListOptions ¶
type ListOptions struct {
// Search matches slug, title and destination URL.
Search string
// FolderID filters by folder.
FolderID int64
// Tag filters by tag name.
Tag string
// Status filters by status: active, disabled, archived, expired,
// exhausted, blocked, pending_review.
Status string
// Page is the page number.
Page int
// PerPage is 1-100 (API default 25).
PerPage int
}
ListOptions are the filters for LinksService.List and LinksService.Iter. Zero values are omitted from the query.
type Meta ¶
type Meta struct {
CurrentPage int `json:"current_page"`
From int `json:"from"`
LastPage int `json:"last_page"`
PerPage int `json:"per_page"`
To int `json:"to"`
Total int `json:"total"`
}
Meta is Laravel-style pagination metadata.
type NotFoundError ¶
type NotFoundError struct {
// contains filtered or unexported fields
}
NotFoundError is returned for 404 responses. Requesting a link you don't own also returns 404 (never 403).
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
Unwrap returns the base *Error.
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithBaseURL ¶
WithBaseURL overrides the base URL (default https://in.bio).
func WithHTTPClient ¶
WithHTTPClient supplies a custom *http.Client, e.g. to configure proxies or transports. Its Timeout takes precedence over WithTimeout.
func WithMaxRetries ¶
WithMaxRetries sets the maximum number of retries (default 2). Only idempotent GET requests and 429 responses that carry a Retry-After header are retried, with exponential backoff capped at 10s.
func WithTimeout ¶
WithTimeout sets the request timeout (default 30s). It applies to the client's own HTTP client; when WithHTTPClient is used, the supplied client's Timeout governs instead.
func WithToken ¶
WithToken sets the API bearer token. When omitted, the client falls back to the INBIO_API_TOKEN environment variable. A token is not required for the free Client.Shorten endpoint.
type PageLinks ¶
type PageLinks struct {
First *string `json:"first"`
Last *string `json:"last"`
Prev *string `json:"prev"`
Next *string `json:"next"`
}
PageLinks are Laravel-style pagination URLs. Prev and Next are nil on the first and last page respectively.
type QRCode ¶
type QRCode struct {
// Data is the raw image bytes; write them to a file directly, e.g.
// os.WriteFile("qr.png", qr.Data, 0o644).
Data []byte
// ContentType is "image/png" or "image/svg+xml".
ContentType string
}
QRCode is a rendered QR code image. The QR encodes the short URL, so destination edits never invalidate printed codes.
type QROptions ¶
type QROptions struct {
// Format is "png" (default) or "svg".
Format string
// Size is 64-2048 px.
Size int
}
QROptions are the options for LinksService.QR.
type RateLimitError ¶
type RateLimitError struct {
// RetryAfter is the number of seconds to wait before retrying, from the
// Retry-After header (0 when absent).
RetryAfter int
// contains filtered or unexported fields
}
RateLimitError is returned for 429 responses once retries are exhausted (or when the response carries no Retry-After header).
func (*RateLimitError) Unwrap ¶
func (e *RateLimitError) Unwrap() error
Unwrap returns the base *Error.
type ServerError ¶
type ServerError struct {
// contains filtered or unexported fields
}
ServerError is returned for 5xx responses.
type ShortenResult ¶
type ShortenResult struct {
ShortURL string `json:"short_url"`
Slug string `json:"slug"`
QRURL string `json:"qr_url"`
PreviewURL string `json:"preview_url"`
ClaimURL string `json:"claim_url"`
Expires string `json:"expires"`
Docs string `json:"docs"`
}
ShortenResult is the response of the free keyless shorten endpoint.
type SignatureVerificationError ¶
type SignatureVerificationError struct {
// Message describes why verification failed.
Message string
}
SignatureVerificationError is returned by webhook verification when the signature header is malformed, the signature does not match, or the timestamp is outside the tolerance.
func (*SignatureVerificationError) Error ¶
func (e *SignatureVerificationError) Error() string
Error implements the error interface.
type StateConflictError ¶
type StateConflictError struct {
// Current is the link's current status, e.g. "expired".
Current string
// contains filtered or unexported fields
}
StateConflictError is returned for 409 responses (invalid state transition, e.g. enabling a link that is expired rather than disabled).
func (*StateConflictError) Unwrap ¶
func (e *StateConflictError) Unwrap() error
Unwrap returns the base *Error.
type Tag ¶
type Tag struct {
ID int64 `json:"id"`
Name string `json:"name"`
LinksCount int `json:"links_count"`
CreatedAt time.Time `json:"created_at"`
}
Tag is a link tag.
type TagsService ¶
type TagsService struct {
// contains filtered or unexported fields
}
TagsService provides access to the tag endpoints. Access it via Client.Tags.
type UTM ¶
type UTM struct {
Source string `json:"source,omitempty"`
Medium string `json:"medium,omitempty"`
Campaign string `json:"campaign,omitempty"`
Term string `json:"term,omitempty"`
Content string `json:"content,omitempty"`
}
UTM are the UTM parameters attached to a link.
type UpdateLinkParams ¶
type UpdateLinkParams struct {
// DestinationURL requires the edit destination feature (Pro+) and
// re-triggers a safety scan.
DestinationURL *string `json:"destination_url,omitempty"`
Slug *string `json:"slug,omitempty"`
Title *string `json:"title,omitempty"`
Description *string `json:"description,omitempty"`
Notes *string `json:"notes,omitempty"`
RedirectType *int `json:"redirect_type,omitempty"`
FolderID *int64 `json:"folder_id,omitempty"`
Tags []string `json:"tags,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
FallbackURL *string `json:"fallback_url,omitempty"`
ClickLimit *int `json:"click_limit,omitempty"`
Password *string `json:"password,omitempty"`
UTM *UTM `json:"utm,omitempty"`
}
UpdateLinkParams are the fields for LinksService.Update. All fields are pointers: nil fields are left unchanged. Use the String, Int, Int64 and Time helpers for literals.
type Usage ¶
type Usage struct {
Plan string `json:"plan"`
PeriodStart string `json:"period_start"`
Usage UsageCounters `json:"usage"`
Limits UsageLimits `json:"limits"`
}
Usage is the account usage report for the current billing period.
type UsageCounters ¶
type UsageCounters struct {
LinksCreated int64 `json:"links_created"`
HumanClicks int64 `json:"human_clicks"`
APIRequests int64 `json:"api_requests"`
}
UsageCounters are the consumed amounts this period.
type UsageLimits ¶
type UsageLimits struct {
LinksPerMonth int64 `json:"links_per_month"`
HumanClicksPerMonth int64 `json:"human_clicks_per_month"`
APIRequestsPerMinute int64 `json:"api_requests_per_minute"`
}
UsageLimits are the plan limits.
type ValidationError ¶
type ValidationError struct {
// Errors maps field names to their validation error messages.
Errors map[string][]string
// contains filtered or unexported fields
}
ValidationError is returned for 422 validation failures, and for the free shorten endpoint's `{"error": "..."}` shape.
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
Unwrap returns the base *Error.
type WebhooksService ¶
type WebhooksService struct{}
WebhooksService verifies webhook signatures. It is a pure crypto helper and performs no HTTP requests. Access it via Client.Webhooks, or use it directly: (&inbio.WebhooksService{}).Verify(...).
func (*WebhooksService) ConstructEvent ¶
func (s *WebhooksService) ConstructEvent(payload []byte, signatureHeader, secret string, tolerance time.Duration) (*Event, error)
ConstructEvent is an alias for WebhooksService.Verify.
func (*WebhooksService) Verify ¶
func (s *WebhooksService) Verify(payload []byte, signatureHeader, secret string, tolerance time.Duration) (*Event, error)
Verify checks a webhook delivery's signature and returns the parsed event.
- payload is the exact raw request body (before any JSON decoding).
- signatureHeader is the X-Inbio-Signature header value, of the form "t=<unix>,v1=<hex>" where v1 = HMAC-SHA256(secret, "<t>.<raw body>").
- secret is the endpoint's signing secret.
- tolerance is the allowed clock skew; pass 0 to use DefaultWebhookTolerance (300s).
The comparison is constant-time. A SignatureVerificationError is returned when the header is malformed, the timestamp is stale (replay protection) or the signature does not match.