inbio

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 16 Imported by: 0

README

inbio-go — official Go SDK for INBIO (in.bio)

The official Go SDK for INBIO, the premium URL shortener with click analytics and customizable QR codes. Shorten links, generate styled QR codes, read analytics, and manage folders and tags from Go.

  • Free to startinbio.Shorten() and the QR API need no account and no API key
  • Zero dependencies — standard library only; context-first API, functional options, range-over-func iteration (Go ≥ 1.23)
  • Complete — covers the entire INBIO REST API: links CRUD, iteration, bulk create, QR codes, analytics, webhook signature verification

Install

go get github.com/getinbio/inbio-go

Shorten a URL — no account needed

The free endpoint requires no token, no account, nothing:

result, err := inbio.Shorten(ctx, "https://example.com/some/very/long/url")
fmt.Println(result.ShortURL) // https://in.bio/x7Kp2q

Anonymous links are deleted after 30 days unless claimed via result.ClaimURL. Rate limit: 5/min per IP (100/day).

Authenticated quickstart

Create a token under Settings → API tokens (API access requires Pro or Business). Pass it explicitly or set INBIO_API_TOKEN:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/getinbio/inbio-go"
)

func main() {
	ctx := context.Background()
	client := inbio.NewClient(inbio.WithToken("your-api-token"))

	link, err := client.Links.Create(ctx, inbio.CreateLinkParams{
		DestinationURL: "https://example.com/sale",
		Slug:           "spring-sale",
		Tags:           []string{"marketing"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(link.ShortURL) // https://in.bio/spring-sale
}
List and iterate

List returns one page; Iter walks every page for you:

page, err := client.Links.List(ctx, &inbio.ListOptions{
	Status:  "active",
	PerPage: 50,
})
fmt.Println(page.Meta.Total, page.HasNext())

// Auto-pagination over every matching link:
for link, err := range client.Links.Iter(ctx, &inbio.ListOptions{Tag: "marketing"}) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(link.Slug, link.TotalClicks)
}

ListOptions supports Search, FolderID, Tag, Status, Page, PerPage.

Create with options

Only DestinationURL is required; zero-valued fields are omitted:

link, err := client.Links.Create(ctx, inbio.CreateLinkParams{
	DestinationURL: "https://example.com/launch",
	Title:          "Launch post",
	RedirectType:   301,
	FolderID:       3,
	Tags:           []string{"launch", "blog"},
	ExpiresAt:      inbio.Time(time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC)),
	ClickLimit:     10000,
	Password:       "s3cret", // Pro+
	UTM:            &inbio.UTM{Source: "newsletter", Campaign: "q3"},
})
Update, enable, disable

UpdateLinkParams uses pointers so only the fields you set are sent (helpers: inbio.String, inbio.Int, inbio.Int64, inbio.Time):

link, err := client.Links.Update(ctx, link.ID, inbio.UpdateLinkParams{
	Title: inbio.String("New title"),
	Slug:  inbio.String("summer-sale"),
})

link, err = client.Links.Disable(ctx, link.ID) // active -> disabled
link, err = client.Links.Enable(ctx, link.ID)  // disabled -> active
err = client.Links.Delete(ctx, link.ID)        // soft delete, stops redirecting

Enable/disable from any other status returns a *inbio.StateConflictError carrying the link's Current status.

Bulk create (Business)

Up to 100 links per request; rows fail independently:

result, err := client.Links.BulkCreate(ctx, []inbio.CreateLinkParams{
	{DestinationURL: "https://example.com/1", Slug: "promo-1"},
	{DestinationURL: "https://example.com/2", Slug: "promo-2"},
})
for _, f := range result.Failed {
	fmt.Printf("row %d failed: %s\n", f.Index, f.Error)
}
QR code to file
qr, err := client.Links.QR(ctx, link.ID, &inbio.QROptions{Format: "png", Size: 512})
if err != nil {
	log.Fatal(err)
}
_ = os.WriteFile("qr.png", qr.Data, 0o644) // qr.ContentType == "image/png"

The QR encodes the short URL, so destination edits never invalidate printed codes.

Analytics
a, err := client.Links.Analytics(ctx, link.ID, &inbio.AnalyticsOptions{
	From: "2026-06-01",
	To:   "2026-06-30",
})
fmt.Println(a.Totals.Clicks, a.Totals.Uniques)
for _, c := range a.Countries {
	fmt.Println(c.Value, c.Clicks)
}

Folders and tags

folders, err := client.Folders.List(ctx)
tags, err := client.Tags.List(ctx)

Account usage

usage, err := client.Account.Usage(ctx)
fmt.Println(usage.Plan)                       // "pro"
fmt.Println(usage.Usage.LinksCreated)         // 120
fmt.Println(usage.Limits.LinksPerMonth)       // 2000

Webhook verification

Verify the X-Inbio-Signature header over the exact raw request body. The comparison is constant-time and stale timestamps are rejected (default tolerance 300s; pass a time.Duration to change it):

func handleWebhook(w http.ResponseWriter, r *http.Request) {
	payload, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "read error", http.StatusBadRequest)
		return
	}

	event, err := client.Webhooks.Verify(
		payload,
		r.Header.Get("X-Inbio-Signature"),
		os.Getenv("INBIO_WEBHOOK_SECRET"),
		0, // 0 = default 300s tolerance
	)
	if err != nil {
		http.Error(w, "invalid signature", http.StatusBadRequest)
		return
	}

	switch event.Event {
	case "link.clicked":
		link, _ := event.Link()
		fmt.Println("clicked:", link.Slug)
	case "link.click_limit_reached":
		// ...
	}
	w.WriteHeader(http.StatusOK)
}

Webhooks.ConstructEvent is an alias for Verify.

Error handling

Every non-2xx response maps to a typed error; all of them wrap the base *inbio.Error (fields StatusCode, Type, Message, Body), so errors.As works at either level:

link, err := client.Links.Get(ctx, 42)
if err != nil {
	var notFound *inbio.NotFoundError
	var rateLimited *inbio.RateLimitError
	switch {
	case errors.As(err, &notFound):
		fmt.Println("no such link")
	case errors.As(err, &rateLimited):
		time.Sleep(time.Duration(rateLimited.RetryAfter) * time.Second)
	default:
		return err
	}
}
Error Status Extra fields
*inbio.AuthenticationError 401
*inbio.AccessError 403 Type (plan/scope/account), Required scope
*inbio.NotFoundError 404 also returned for links you don't own
*inbio.StateConflictError 409 Current status
*inbio.ValidationError 422 Errors map[string][]string per field
*inbio.EntitlementError 422 plan feature/limit (error.type=entitlement)
*inbio.RateLimitError 429 RetryAfter seconds
*inbio.ServerError 5xx
*inbio.SignatureVerificationError webhook verification failures

Retries and timeouts

Defaults: 30s timeout, 2 retries. Retries apply only to idempotent GET requests (on transport errors and 5xx) and to 429 responses that carry a Retry-After header, with exponential backoff capped at 10s.

client := inbio.NewClient(
	inbio.WithToken("your-api-token"),
	inbio.WithBaseURL("https://in.bio"),        // default
	inbio.WithTimeout(10*time.Second),
	inbio.WithMaxRetries(5),
	inbio.WithHTTPClient(&http.Client{ /* custom transport */ }),
)

Authenticating via environment variable

When no token is passed, the client reads INBIO_API_TOKEN:

export INBIO_API_TOKEN="your-api-token"
client := inbio.NewClient() // uses INBIO_API_TOKEN

About INBIO

INBIO (in.bio) is a URL shortener and link-management platform: short links with custom slugs, real-time click analytics (countries, devices, browsers, referrers — bots filtered out), a QR code studio with dot styles, marker shapes and colors, folders, tags, UTM tools, and a REST API with webhooks. Free plan included.

License

MIT © InBio, Inc.

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

View Source
const DefaultWebhookTolerance = 300 * time.Second

DefaultWebhookTolerance is the default allowed clock skew between the signature timestamp and now.

View Source
const EnvToken = "INBIO_API_TOKEN"

EnvToken is the environment variable consulted for an API token when none is supplied with WithToken.

View Source
const Version = "0.1.0"

Version is the version of this SDK.

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to v. Helper for optional params.

func Int

func Int(v int) *int

Int returns a pointer to v. Helper for optional params.

func Int64

func Int64(v int64) *int64

Int64 returns a pointer to v. Helper for optional params.

func String

func String(v string) *string

String returns a pointer to v. Helper for optional params.

func Time

func Time(v time.Time) *time.Time

Time returns a pointer to v. Helper for optional params.

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).

func (*AccessError) Unwrap

func (e *AccessError) Unwrap() error

Unwrap returns the base *Error.

type AccountService

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

AccountService provides access to the account endpoints. Access it via Client.Account.

func (*AccountService) Usage

func (s *AccountService) Usage(ctx context.Context) (*Usage, error)

Usage returns the account's usage and limits for the current billing period (GET /account/usage, any scope).

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

type AnalyticsCount struct {
	Value  string `json:"value"`
	Clicks int64  `json:"clicks"`
}

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

type AnalyticsRange struct {
	From string `json:"from"`
	To   string `json:"to"`
}

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.

func NewClient

func NewClient(opts ...Option) *Client

NewClient returns a new in.bio API client. When no token is supplied via WithToken, the INBIO_API_TOKEN environment variable is used.

func (*Client) Shorten

func (c *Client) Shorten(ctx context.Context, longURL string) (*ShortenResult, error)

Shorten shortens a URL using the free keyless endpoint (POST /api/shorten). See the package-level Shorten for details.

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, &notFound) { ... } // a specific one

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

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.

func (e *Event) Link() (*Link, error)

Link decodes the event's Data as a Link. Only meaningful for link.* events.

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.

func (*FoldersService) List

func (s *FoldersService) List(ctx context.Context) ([]Folder, error)

List returns all folders (GET /folders, scope links:read).

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.

func (*LinkPage) HasNext

func (p *LinkPage) HasNext() bool

HasNext reports whether another page follows this one.

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

func (s *LinksService) Disable(ctx context.Context, id int64) (*Link, error)

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

func (s *LinksService) Enable(ctx context.Context, id int64) (*Link, error)

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) Get

func (s *LinksService) Get(ctx context.Context, id int64) (*Link, error)

Get fetches a link by id (GET /links/{id}, scope links:read).

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

func (s *LinksService) QR(ctx context.Context, id int64, opts *QROptions) (*QRCode, error)

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

func WithBaseURL(baseURL string) Option

WithBaseURL overrides the base URL (default https://in.bio).

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient supplies a custom *http.Client, e.g. to configure proxies or transports. Its Timeout takes precedence over WithTimeout.

func WithMaxRetries

func WithMaxRetries(n int) Option

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

func WithTimeout(d time.Duration) Option

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

func WithToken(token string) Option

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 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.

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

Unwrap returns the base *Error.

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.

func Shorten

func Shorten(ctx context.Context, longURL string) (*ShortenResult, error)

Shorten shortens a URL using the free keyless endpoint (POST /api/shorten). No account or API token is required. Anonymous links expire after 30 days unless claimed via the returned claim URL.

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

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.

func (*TagsService) List

func (s *TagsService) List(ctx context.Context) ([]Tag, error)

List returns all tags (GET /tags, scope links:read).

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.

Jump to

Keyboard shortcuts

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