r4m

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 16 Imported by: 0

README

sdk-go

Official Go client for the r4m.ai route optimization API: the optimal driving order for a list of stops on real roads, with delivery windows, service times and fleets, plus geocoding.

Install

go get github.com/r4m-ai/sdk-go

Optimize a route

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	r4m "github.com/r4m-ai/sdk-go"
)

func main() {
	ctx := context.Background()

	client, err := r4m.New(os.Getenv("R4M_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	// Submits, waits for the solver (usually 2–60 seconds) and returns the
	// finished plan. Addresses without Lat/Lng are geocoded in the same call.
	optimization, err := client.CreateOptimizationAndWaitForRoutes(ctx, r4m.CreateOptimizationRequest{
		Addresses: []r4m.Address{
			{Address: "Depot", Lat: r4m.Ptr(40.7128), Lng: r4m.Ptr(-74.006), IsDepot: r4m.Ptr(true)},
			{Address: "Stop 1", Lat: r4m.Ptr(40.758), Lng: r4m.Ptr(-73.9855)},
			{Address: "Stop 2", Lat: r4m.Ptr(40.7484), Lng: r4m.Ptr(-73.9857)},
		},
	}, r4m.WaitOptions{})
	if err != nil {
		log.Fatal(err)
	}

	for _, stop := range optimization.Result.Routes[0].Waypoints {
		fmt.Println(stop.Index)
	}
}

Waypoints is the driving order; each Index points back into the addresses you sent. Always check Result.UnroutedStops: a stop listed there could not be fitted and is not in the plan.

Errors

Every call returns the value or an error. A refusal from the API is an *r4m.ApiError; anything else never got an answer, such as a network failure.

account, err := client.GetAccount(ctx)
if err != nil {
	var apiErr *r4m.ApiError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.Code, apiErr.Status, apiErr.Message)
	}
	log.Fatal(err)
}
fmt.Println(account.PlanTier)

Waiting adds three more: *r4m.OptimizationFailedError, *r4m.OptimizationTimeoutError and *r4m.BusyError.

Full reference: r4m.ai/docs/sdks.

License

MIT

Documentation

Overview

Package r4m provides primitives to interact with the openapi HTTP API.

Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.4.1 DO NOT EDIT.

Index

Constants

View Source
const (
	DefaultWaitTimeout  = 5 * time.Minute
	DefaultInitialDelay = 2 * time.Second
	DefaultMaxDelay     = 5 * time.Second
	// DefaultBusyTimeout is how long "busy" is acceptable before a call fails.
	DefaultBusyTimeout = 2 * time.Minute
	// DefaultActivePoll is how often WaitForActiveOptimizations looks.
	DefaultActivePoll = 5 * time.Second
)
View Source
const (
	EventOptimizationCompleted = "optimization.completed"
	EventOptimizationFailed    = "optimization.failed"
)

The event names carried in WebhookEvent.Type.

View Source
const (
	BearerAuthScopes = "bearerAuth.Scopes"
)
View Source
const DefaultBaseURL = "https://r4m.ai"

DefaultBaseURL is baked in at generation time so New needs nothing but an API key.

View Source
const WebhookSignatureHeader = "X-Webhook-Signature"

WebhookSignatureHeader carries the HMAC-SHA256 hex digest of the raw body.

Variables

View Source
var ErrWebhookSignature = errors.New("webhook signature did not match")

ErrWebhookSignature reports a delivery whose signature did not match. Treat as hostile: reject with a 401.

Functions

func NewBulkGeocodeRequest

func NewBulkGeocodeRequest(server string, body BulkGeocodeJSONRequestBody) (*http.Request, error)

NewBulkGeocodeRequest calls the generic BulkGeocode builder with application/json body

func NewBulkGeocodeRequestWithBody

func NewBulkGeocodeRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewBulkGeocodeRequestWithBody generates requests for BulkGeocode with any type of body

func NewCreateApiKeyRequest

func NewCreateApiKeyRequest(server string, body CreateApiKeyJSONRequestBody) (*http.Request, error)

NewCreateApiKeyRequest calls the generic CreateApiKey builder with application/json body

func NewCreateApiKeyRequestWithBody

func NewCreateApiKeyRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewCreateApiKeyRequestWithBody generates requests for CreateApiKey with any type of body

func NewCreateOptimizationRequest

func NewCreateOptimizationRequest(server string, body CreateOptimizationJSONRequestBody) (*http.Request, error)

NewCreateOptimizationRequest calls the generic CreateOptimization builder with application/json body

func NewCreateOptimizationRequestWithBody

func NewCreateOptimizationRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewCreateOptimizationRequestWithBody generates requests for CreateOptimization with any type of body

func NewDeleteOptimizationRequest

func NewDeleteOptimizationRequest(server string, id openapi_types.UUID) (*http.Request, error)

NewDeleteOptimizationRequest generates requests for DeleteOptimization

func NewForwardGeocodeRequest

func NewForwardGeocodeRequest(server string, body ForwardGeocodeJSONRequestBody) (*http.Request, error)

NewForwardGeocodeRequest calls the generic ForwardGeocode builder with application/json body

func NewForwardGeocodeRequestWithBody

func NewForwardGeocodeRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewForwardGeocodeRequestWithBody generates requests for ForwardGeocode with any type of body

func NewGetAccountRequest

func NewGetAccountRequest(server string) (*http.Request, error)

NewGetAccountRequest generates requests for GetAccount

func NewGetOptimizationRequest

func NewGetOptimizationRequest(server string, id openapi_types.UUID) (*http.Request, error)

NewGetOptimizationRequest generates requests for GetOptimization

func NewGetUsageRequest

func NewGetUsageRequest(server string) (*http.Request, error)

NewGetUsageRequest generates requests for GetUsage

func NewGetWebhookSecretRequest added in v1.3.6

func NewGetWebhookSecretRequest(server string) (*http.Request, error)

NewGetWebhookSecretRequest generates requests for GetWebhookSecret

func NewListApiKeysRequest

func NewListApiKeysRequest(server string) (*http.Request, error)

NewListApiKeysRequest generates requests for ListApiKeys

func NewListOptimizationsRequest

func NewListOptimizationsRequest(server string, params *ListOptimizationsParams) (*http.Request, error)

NewListOptimizationsRequest generates requests for ListOptimizations

func NewRevokeApiKeyRequest

func NewRevokeApiKeyRequest(server string, id openapi_types.UUID) (*http.Request, error)

NewRevokeApiKeyRequest generates requests for RevokeApiKey

func NewTopupCreditsRequest

func NewTopupCreditsRequest(server string, body TopupCreditsJSONRequestBody) (*http.Request, error)

NewTopupCreditsRequest calls the generic TopupCredits builder with application/json body

func NewTopupCreditsRequestWithBody

func NewTopupCreditsRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error)

NewTopupCreditsRequestWithBody generates requests for TopupCredits with any type of body

func Ptr added in v1.4.0

func Ptr[T any](v T) *T

Ptr returns a pointer to v, because every optional field is a pointer:

r4m.Address{Address: "Depot", IsDepot: r4m.Ptr(true)}

Types

type API added in v1.4.0

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

API is the client for your account. Every call returns the value you asked for and an error; see api.go.

func New added in v1.4.0

func New(apiKey string, opts ...ClientOption) (*API, error)

New builds a client for your account. Nothing is sent — this only holds your credentials until the first call.

WithBaseURL exists for r4m.ai's own staging deployments and must be https: a plain-http URL (other than localhost) would send the API key in clear text, so it is refused.

func (*API) BulkGeocode added in v1.4.0

func (c *API) BulkGeocode(ctx context.Context, body BulkGeocodeRequest) (*BulkGeocoding, error)

BulkGeocode converts many addresses to coordinates in one request: one result per distinct address, to be matched by Original, never by position.

func (*API) CreateApiKey added in v1.4.0

func (c *API) CreateApiKey(ctx context.Context, body CreateApiKeyRequest) (*ApiKeyCreated, error)

CreateApiKey generates an API key. The raw key is in this answer only.

func (*API) CreateOptimization added in v1.4.0

func (c *API) CreateOptimization(ctx context.Context, body CreateOptimizationRequest) (*Optimization, error)

CreateOptimization submits an optimization and returns the receipt (status pending). A 429 comes back as an *ApiError; SubmitOptimization waits it out.

func (*API) CreateOptimizationAndWaitForRoutes added in v1.4.0

func (c *API) CreateOptimizationAndWaitForRoutes(
	ctx context.Context,
	body CreateOptimizationRequest,
	opts WaitOptions,
) (*Optimization, error)

CreateOptimizationAndWaitForRoutes submits an optimization and waits for the finished plan.

Equivalent to SubmitOptimization followed by WaitForRoutes, for the common case where both happen in the same place. A WebhookUrl may still be set — you will simply be notified as well.

func (*API) DeleteOptimization added in v1.4.0

func (c *API) DeleteOptimization(ctx context.Context, id openapi_types.UUID) error

DeleteOptimization permanently deletes an optimization and its result.

func (*API) ForwardGeocode added in v1.4.0

func (c *API) ForwardGeocode(ctx context.Context, body ForwardGeocodeRequest) (*ForwardGeocoding, error)

ForwardGeocode converts one address to coordinates.

func (*API) GetAccount added in v1.4.0

func (c *API) GetAccount(ctx context.Context) (*Account, error)

GetAccount returns your account and plan.

func (*API) GetOptimization added in v1.4.0

func (c *API) GetOptimization(ctx context.Context, id openapi_types.UUID) (*Optimization, error)

GetOptimization fetches one optimization.

func (*API) GetUsage added in v1.4.0

func (c *API) GetUsage(ctx context.Context) (*Usage, error)

GetUsage returns the prepaid balance and recent activity.

func (*API) GetWebhookSecret added in v1.4.0

func (c *API) GetWebhookSecret(ctx context.Context) (*WebhookSecrets, error)

GetWebhookSecret returns the account's webhook signing secrets.

func (*API) ListApiKeys added in v1.4.0

func (c *API) ListApiKeys(ctx context.Context) ([]ApiKey, error)

ListApiKeys lists your API keys; raw keys are never returned.

func (*API) ListOptimizations added in v1.4.0

func (c *API) ListOptimizations(ctx context.Context, params *ListOptimizationsParams) (*OptimizationPage, error)

ListOptimizations lists optimizations, newest first. params may be nil.

func (*API) Raw added in v1.4.0

func (c *API) Raw() *ClientWithResponses

Raw returns the generated client underneath, for whatever API does not cover.

func (*API) RevokeApiKey added in v1.4.0

func (c *API) RevokeApiKey(ctx context.Context, id openapi_types.UUID) error

RevokeApiKey revokes an API key; it stops working immediately.

func (*API) SubmitOptimization added in v1.4.0

func (c *API) SubmitOptimization(
	ctx context.Context,
	body CreateOptimizationRequest,
	opts WaitOptions,
) (*Optimization, error)

SubmitOptimization submits an optimization, waiting out "busy" answers, and returns the receipt (status pending). Use this when you will collect the plan some other way — a webhook, your own poller — but still want the 429s handled. Only OnBusy and BusyTimeout of opts are read.

func (*API) TopupCredits added in v1.4.0

func (c *API) TopupCredits(ctx context.Context, body TopupCreditsJSONRequestBody) (*TopupReceipt, error)

TopupCredits requests a machine-payment top-up. Without a payment receipt the answer is a 402: an *ApiError whose Body holds the payment challenge.

func (*API) WaitForActiveOptimizations added in v1.4.0

func (c *API) WaitForActiveOptimizations(
	ctx context.Context,
	opts ActiveWaitOptions,
) error

WaitForActiveOptimizations returns once the account has nothing pending or processing — the moment a SubmitOptimization is guaranteed a free slot. Useful before a batch, or when OnBusy told you to come back later.

func (*API) WaitForRoutes added in v1.4.0

func (c *API) WaitForRoutes(
	ctx context.Context,
	id openapi_types.UUID,
	opts WaitOptions,
) (*Optimization, error)

WaitForRoutes polls an optimization until it is finished.

Use this when the id came from somewhere else — your own queue, a database row, an earlier process. If you are submitting and waiting in one place, CreateOptimizationAndWaitForRoutes does both.

It backs off 2s, 4s, then every 5s; treats a 429 as busy (see OnBusy); and keeps going through transient network errors and 5xx, since the optimization runs whether or not you stay connected.

type Account

type Account struct {
	// BalanceMicros Current prepaid balance in micro-dollars (1 USD = 1 000 000)
	BalanceMicros int                 `json:"balanceMicros"`
	CreatedAt     *time.Time          `json:"createdAt,omitempty"`
	Currency      AccountCurrency     `json:"currency"`
	Email         openapi_types.Email `json:"email"`
	Id            openapi_types.UUID  `json:"id"`
	Name          *string             `json:"name,omitempty"`

	// Plan The limits this account lives under (capacity, not money). An account on individual terms shows its own agreed numbers.
	Plan struct {
		MaxAddressesPerRequest int `json:"maxAddressesPerRequest"`
		MaxApiKeys             int `json:"maxApiKeys"`

		// MaxConcurrentOptimizations How many optimizations may be pending or processing at once
		MaxConcurrentOptimizations int    `json:"maxConcurrentOptimizations"`
		Name                       string `json:"name"`

		// Parameters Ceiling on each gated optimization parameter: "unavailable" or the largest accepted value
		Parameters struct {
			// MaxRouteDistanceMeters "unavailable" when the plan does not offer the parameter, otherwise the largest value it accepts
			MaxRouteDistanceMeters ParamLimit `json:"maxRouteDistanceMeters"`

			// MaxRouteDurationSeconds "unavailable" when the plan does not offer the parameter, otherwise the largest value it accepts
			MaxRouteDurationSeconds ParamLimit `json:"maxRouteDurationSeconds"`

			// MaxRoutes "unavailable" when the plan does not offer the parameter, otherwise the largest value it accepts
			MaxRoutes ParamLimit `json:"maxRoutes"`
		} `json:"parameters"`

		// Webhook Delivery budget for your webhook endpoint
		Webhook struct {
			MaxAttempts   int `json:"maxAttempts"`
			QstashRetries int `json:"qstashRetries"`
			TimeoutMs     int `json:"timeoutMs"`
		} `json:"webhook"`
	} `json:"plan"`

	// PlanTier Current subscription plan
	PlanTier AccountPlanTier `json:"planTier"`
}

Account defines model for Account.

type AccountCurrency

type AccountCurrency string

AccountCurrency defines model for Account.Currency.

const (
	AccountCurrencyUSD AccountCurrency = "USD"
)

Defines values for AccountCurrency.

type AccountPlanTier

type AccountPlanTier string

AccountPlanTier Current subscription plan

const (
	Custom AccountPlanTier = "custom"
	Free   AccountPlanTier = "free"
	Pro    AccountPlanTier = "pro"
)

Defines values for AccountPlanTier.

type ActiveOptimizationsTimeoutError

type ActiveOptimizationsTimeoutError struct {
	ActiveOptimizationIDs []string
	Timeout               time.Duration
}

ActiveOptimizationsTimeoutError means the account still had optimizations running when the wait ran out.

func (*ActiveOptimizationsTimeoutError) Error

type ActiveWaitEvent

type ActiveWaitEvent struct {
	// Active is how many optimizations are still pending or processing.
	Active                int
	ActiveOptimizationIDs []string
	Elapsed               time.Duration
	// Attempt is 1 for the first look, counting up.
	Attempt int
}

ActiveWaitEvent is one look at what the account still has running.

type ActiveWaitOptions

type ActiveWaitOptions struct {
	// OnWait is called after every look while something is still running,
	// for display.
	OnWait       func(ActiveWaitEvent)
	Timeout      time.Duration
	PollInterval time.Duration
}

ActiveWaitOptions tunes WaitForActiveOptimizations. The zero value is usable.

type Address

type Address struct {
	// Address The stop's address. With `lat`/`lng` it is only a label; without them it is geocoded (charged at the geocode price) and must resolve to exactly one place.
	Address string `json:"address"`

	// IsDepot When true, marks this stop as the route's depot (start and/or end).
	IsDepot *bool `json:"isDepot,omitempty"`

	// Lat Latitude in decimal degrees. Optional: omit both `lat` and `lng` to have the address geocoded.
	Lat *float64 `json:"lat,omitempty"`

	// Lng Longitude in decimal degrees. Goes together with `lat`.
	Lng *float64 `json:"lng,omitempty"`

	// Priority Stop priority (1 = highest). Higher-priority stops are scheduled earlier.
	Priority *int `json:"priority,omitempty"`

	// ServiceTimeSeconds Time spent at this stop, in seconds (service dwell time).
	ServiceTimeSeconds *int `json:"serviceTimeSeconds,omitempty"`

	// TimeWindowEnd Latest local time this stop can be served, HH:MM. The stop's `serviceTimeSeconds` must finish by then, not merely begin.
	TimeWindowEnd *string `json:"timeWindowEnd,omitempty"`

	// TimeWindowStart Earliest local time this stop can be served, HH:MM. Taken as the first such time at or after the route starts, so 02:00 on a route leaving at 22:00 means the following morning.
	TimeWindowStart *string `json:"timeWindowStart,omitempty"`
}

Address defines model for Address.

type ApiError added in v1.4.0

type ApiError struct {
	// Status is the HTTP status.
	Status int
	// Code is machine-readable: an API error code such as INSUFFICIENT_FUNDS,
	// or UNEXPECTED_RESPONSE when the body was not the API's error format.
	Code string
	// Message is the server's own explanation.
	Message string
	// Details is optional machine-readable context. Message stands alone
	// without it.
	Details map[string]any
	// RetryAfter is how long the server asked us to wait, on a 429.
	RetryAfter time.Duration
	// Body is the response body as sent, for fields outside the error envelope.
	Body []byte
}

ApiError means the API refused the request. Reach it with errors.As:

var apiErr *r4m.ApiError
if errors.As(err, &apiErr) && apiErr.Code == "INSUFFICIENT_FUNDS" { ... }

A request that never got an answer returns the underlying network error.

func (*ApiError) Error added in v1.4.0

func (e *ApiError) Error() string

type ApiKey

type ApiKey struct {
	CreatedAt  time.Time          `json:"createdAt"`
	Id         openapi_types.UUID `json:"id"`
	LastUsedAt *time.Time         `json:"lastUsedAt"`
	Name       string             `json:"name"`

	// Prefix Key prefix for identification
	Prefix    string     `json:"prefix"`
	RevokedAt *time.Time `json:"revokedAt"`
}

ApiKey defines model for ApiKey.

type ApiKeyCreated

type ApiKeyCreated struct {
	CreatedAt time.Time          `json:"createdAt"`
	Id        openapi_types.UUID `json:"id"`

	// Key The full API key. Store this securely — it will not be shown again.
	Key  string `json:"key"`
	Name string `json:"name"`

	// Prefix Key prefix for identification (e.g., `acc_abc1`)
	Prefix string `json:"prefix"`
}

ApiKeyCreated defines model for ApiKeyCreated.

type BulkGeocodeJSONRequestBody

type BulkGeocodeJSONRequestBody = BulkGeocodeRequest

BulkGeocodeJSONRequestBody defines body for BulkGeocode for application/json ContentType.

type BulkGeocodeRequest

type BulkGeocodeRequest struct {
	// Addresses Address strings to geocode (1-100). A string sent twice is geocoded and charged once.
	Addresses []string `json:"addresses"`

	// Detailed Return detailed result fields
	Detailed *bool `json:"detailed,omitempty"`

	// Nocache Bypass geocoding cache
	Nocache *bool `json:"nocache,omitempty"`
}

BulkGeocodeRequest defines model for BulkGeocodeRequest.

type BulkGeocodeResponse

type BulkGeocodeResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data struct {
			// PriceMicros What this request cost, in micro-dollars (1 USD = 1 000 000); duplicates are charged once
			PriceMicros int `json:"priceMicros"`

			// Results Exactly one result per distinct address sent, in the order first sent
			Results []GeocodeResult `json:"results"`
		} `json:"data"`
		Success bool `json:"success"`
	}
	JSON400 *ErrorResponse
	JSON401 *ErrorResponse
	JSON402 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseBulkGeocodeResponse

func ParseBulkGeocodeResponse(rsp *http.Response) (*BulkGeocodeResponse, error)

ParseBulkGeocodeResponse parses an HTTP response from a BulkGeocodeWithResponse call

func (BulkGeocodeResponse) Status

func (r BulkGeocodeResponse) Status() string

Status returns HTTPResponse.Status

func (BulkGeocodeResponse) StatusCode

func (r BulkGeocodeResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type BulkGeocoding added in v1.4.0

type BulkGeocoding struct {
	PriceMicros int
	Results     []GeocodeResult
}

BulkGeocoding is the answer to BulkGeocode.

type BusyDecision

type BusyDecision string

BusyDecision is what to do about a busy answer: wait it out, or give up now.

const (
	BusyWait BusyDecision = "wait"
	BusyFail BusyDecision = "fail"
)

type BusyError

type BusyError struct {
	Event BusyEvent
}

BusyError means the API was busy and the call was not allowed to keep waiting.

func (*BusyError) Error

func (e *BusyError) Error() string

type BusyEvent

type BusyEvent struct {
	Reason BusyReason
	// Message is the server's own explanation.
	Message string
	// RetryAfter is how long the server asked us to wait before trying again.
	RetryAfter time.Duration
	// Attempt is 1 for the first busy answer of this call, counting up.
	Attempt int
	// Elapsed is the time spent busy-waiting in this call so far.
	Elapsed time.Duration
	// ActiveOptimizationIDs names the optimizations holding the slots
	// (concurrency only; empty otherwise).
	ActiveOptimizationIDs []string
	// TimedOut reports that BusyTimeout has elapsed. From here on only
	// BusyFail is honoured: a BusyWait returned after the deadline is treated
	// as BusyFail, because the caller already said how long busy is acceptable.
	TimedOut bool
}

BusyEvent describes one busy answer.

type BusyReason

type BusyReason string

BusyReason says which limit answered 429.

const (
	BusyRateLimited              BusyReason = "RATE_LIMITED"
	BusyConcurrencyLimitExceeded BusyReason = "CONCURRENCY_LIMIT_EXCEEDED"
)

type Client

type Client struct {
	// The endpoint of the server conforming to this interface, with scheme,
	// https://api.deepmap.com for example. This can contain a path relative
	// to the server, such as https://api.deepmap.com/dev-test, and all the
	// paths in the swagger spec will be appended to the server.
	Server string

	// Doer for performing requests, typically a *http.Client with any
	// customized settings, such as certificate chains.
	Client HttpRequestDoer

	// A list of callbacks for modifying requests which are generated before sending over
	// the network.
	RequestEditors []RequestEditorFn
}

Client which conforms to the OpenAPI3 specification for this service.

func NewClient

func NewClient(server string, opts ...ClientOption) (*Client, error)

Creates a new Client, with reasonable defaults

func (*Client) BulkGeocode

func (c *Client) BulkGeocode(ctx context.Context, body BulkGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) BulkGeocodeWithBody

func (c *Client) BulkGeocodeWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) CreateApiKey

func (c *Client) CreateApiKey(ctx context.Context, body CreateApiKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) CreateApiKeyWithBody

func (c *Client) CreateApiKeyWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) CreateOptimization

func (c *Client) CreateOptimization(ctx context.Context, body CreateOptimizationJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) CreateOptimizationWithBody

func (c *Client) CreateOptimizationWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) DeleteOptimization

func (c *Client) DeleteOptimization(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) ForwardGeocode

func (c *Client) ForwardGeocode(ctx context.Context, body ForwardGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) ForwardGeocodeWithBody

func (c *Client) ForwardGeocodeWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) GetAccount

func (c *Client) GetAccount(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) GetOptimization

func (c *Client) GetOptimization(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) GetUsage

func (c *Client) GetUsage(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) GetWebhookSecret added in v1.3.6

func (c *Client) GetWebhookSecret(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) ListApiKeys

func (c *Client) ListApiKeys(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) ListOptimizations

func (c *Client) ListOptimizations(ctx context.Context, params *ListOptimizationsParams, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) RevokeApiKey

func (c *Client) RevokeApiKey(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) TopupCredits

func (c *Client) TopupCredits(ctx context.Context, body TopupCreditsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

func (*Client) TopupCreditsWithBody

func (c *Client) TopupCreditsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

type ClientInterface

type ClientInterface interface {
	// GetAccount request
	GetAccount(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// TopupCreditsWithBody request with any body
	TopupCreditsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	TopupCredits(ctx context.Context, body TopupCreditsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// BulkGeocodeWithBody request with any body
	BulkGeocodeWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	BulkGeocode(ctx context.Context, body BulkGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// ForwardGeocodeWithBody request with any body
	ForwardGeocodeWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	ForwardGeocode(ctx context.Context, body ForwardGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// ListApiKeys request
	ListApiKeys(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// CreateApiKeyWithBody request with any body
	CreateApiKeyWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	CreateApiKey(ctx context.Context, body CreateApiKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// RevokeApiKey request
	RevokeApiKey(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error)

	// ListOptimizations request
	ListOptimizations(ctx context.Context, params *ListOptimizationsParams, reqEditors ...RequestEditorFn) (*http.Response, error)

	// CreateOptimizationWithBody request with any body
	CreateOptimizationWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)

	CreateOptimization(ctx context.Context, body CreateOptimizationJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)

	// DeleteOptimization request
	DeleteOptimization(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error)

	// GetOptimization request
	GetOptimization(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*http.Response, error)

	// GetUsage request
	GetUsage(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// GetWebhookSecret request
	GetWebhookSecret(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)
}

The interface specification for the client above.

type ClientOption

type ClientOption func(*Client) error

ClientOption allows setting custom parameters during construction

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL overrides the baseURL.

func WithHTTPClient

func WithHTTPClient(doer HttpRequestDoer) ClientOption

WithHTTPClient allows overriding the default Doer, which is automatically created using http.Client. This is useful for tests.

func WithRequestEditorFn

func WithRequestEditorFn(fn RequestEditorFn) ClientOption

WithRequestEditorFn allows setting up a callback function, which will be called right before sending the request. This can be used to mutate the request.

type ClientWithResponses

type ClientWithResponses struct {
	ClientInterface
}

ClientWithResponses builds on ClientInterface to offer response payloads

func NewClientWithResponses

func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error)

NewClientWithResponses creates a new ClientWithResponses, which wraps Client with return type handling

func (*ClientWithResponses) BulkGeocodeWithBodyWithResponse

func (c *ClientWithResponses) BulkGeocodeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BulkGeocodeResponse, error)

BulkGeocodeWithBodyWithResponse request with arbitrary body returning *BulkGeocodeResponse

func (*ClientWithResponses) BulkGeocodeWithResponse

func (c *ClientWithResponses) BulkGeocodeWithResponse(ctx context.Context, body BulkGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*BulkGeocodeResponse, error)

func (*ClientWithResponses) CreateApiKeyWithBodyWithResponse

func (c *ClientWithResponses) CreateApiKeyWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateApiKeyResponse, error)

CreateApiKeyWithBodyWithResponse request with arbitrary body returning *CreateApiKeyResponse

func (*ClientWithResponses) CreateApiKeyWithResponse

func (c *ClientWithResponses) CreateApiKeyWithResponse(ctx context.Context, body CreateApiKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateApiKeyResponse, error)

func (*ClientWithResponses) CreateOptimizationWithBodyWithResponse

func (c *ClientWithResponses) CreateOptimizationWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateOptimizationResponse, error)

CreateOptimizationWithBodyWithResponse request with arbitrary body returning *CreateOptimizationResponse

func (*ClientWithResponses) CreateOptimizationWithResponse

func (c *ClientWithResponses) CreateOptimizationWithResponse(ctx context.Context, body CreateOptimizationJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateOptimizationResponse, error)

func (*ClientWithResponses) DeleteOptimizationWithResponse

func (c *ClientWithResponses) DeleteOptimizationWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*DeleteOptimizationResponse, error)

DeleteOptimizationWithResponse request returning *DeleteOptimizationResponse

func (*ClientWithResponses) ForwardGeocodeWithBodyWithResponse

func (c *ClientWithResponses) ForwardGeocodeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ForwardGeocodeResponse, error)

ForwardGeocodeWithBodyWithResponse request with arbitrary body returning *ForwardGeocodeResponse

func (*ClientWithResponses) ForwardGeocodeWithResponse

func (c *ClientWithResponses) ForwardGeocodeWithResponse(ctx context.Context, body ForwardGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*ForwardGeocodeResponse, error)

func (*ClientWithResponses) GetAccountWithResponse

func (c *ClientWithResponses) GetAccountWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetAccountResponse, error)

GetAccountWithResponse request returning *GetAccountResponse

func (*ClientWithResponses) GetOptimizationWithResponse

func (c *ClientWithResponses) GetOptimizationWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetOptimizationResponse, error)

GetOptimizationWithResponse request returning *GetOptimizationResponse

func (*ClientWithResponses) GetUsageWithResponse

func (c *ClientWithResponses) GetUsageWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetUsageResponse, error)

GetUsageWithResponse request returning *GetUsageResponse

func (*ClientWithResponses) GetWebhookSecretWithResponse added in v1.3.6

func (c *ClientWithResponses) GetWebhookSecretWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetWebhookSecretResponse, error)

GetWebhookSecretWithResponse request returning *GetWebhookSecretResponse

func (*ClientWithResponses) ListApiKeysWithResponse

func (c *ClientWithResponses) ListApiKeysWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListApiKeysResponse, error)

ListApiKeysWithResponse request returning *ListApiKeysResponse

func (*ClientWithResponses) ListOptimizationsWithResponse

func (c *ClientWithResponses) ListOptimizationsWithResponse(ctx context.Context, params *ListOptimizationsParams, reqEditors ...RequestEditorFn) (*ListOptimizationsResponse, error)

ListOptimizationsWithResponse request returning *ListOptimizationsResponse

func (*ClientWithResponses) RevokeApiKeyWithResponse

func (c *ClientWithResponses) RevokeApiKeyWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*RevokeApiKeyResponse, error)

RevokeApiKeyWithResponse request returning *RevokeApiKeyResponse

func (*ClientWithResponses) TopupCreditsWithBodyWithResponse

func (c *ClientWithResponses) TopupCreditsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TopupCreditsResponse, error)

TopupCreditsWithBodyWithResponse request with arbitrary body returning *TopupCreditsResponse

func (*ClientWithResponses) TopupCreditsWithResponse

func (c *ClientWithResponses) TopupCreditsWithResponse(ctx context.Context, body TopupCreditsJSONRequestBody, reqEditors ...RequestEditorFn) (*TopupCreditsResponse, error)

type ClientWithResponsesInterface

type ClientWithResponsesInterface interface {
	// GetAccountWithResponse request
	GetAccountWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetAccountResponse, error)

	// TopupCreditsWithBodyWithResponse request with any body
	TopupCreditsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TopupCreditsResponse, error)

	TopupCreditsWithResponse(ctx context.Context, body TopupCreditsJSONRequestBody, reqEditors ...RequestEditorFn) (*TopupCreditsResponse, error)

	// BulkGeocodeWithBodyWithResponse request with any body
	BulkGeocodeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BulkGeocodeResponse, error)

	BulkGeocodeWithResponse(ctx context.Context, body BulkGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*BulkGeocodeResponse, error)

	// ForwardGeocodeWithBodyWithResponse request with any body
	ForwardGeocodeWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ForwardGeocodeResponse, error)

	ForwardGeocodeWithResponse(ctx context.Context, body ForwardGeocodeJSONRequestBody, reqEditors ...RequestEditorFn) (*ForwardGeocodeResponse, error)

	// ListApiKeysWithResponse request
	ListApiKeysWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListApiKeysResponse, error)

	// CreateApiKeyWithBodyWithResponse request with any body
	CreateApiKeyWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateApiKeyResponse, error)

	CreateApiKeyWithResponse(ctx context.Context, body CreateApiKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateApiKeyResponse, error)

	// RevokeApiKeyWithResponse request
	RevokeApiKeyWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*RevokeApiKeyResponse, error)

	// ListOptimizationsWithResponse request
	ListOptimizationsWithResponse(ctx context.Context, params *ListOptimizationsParams, reqEditors ...RequestEditorFn) (*ListOptimizationsResponse, error)

	// CreateOptimizationWithBodyWithResponse request with any body
	CreateOptimizationWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateOptimizationResponse, error)

	CreateOptimizationWithResponse(ctx context.Context, body CreateOptimizationJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateOptimizationResponse, error)

	// DeleteOptimizationWithResponse request
	DeleteOptimizationWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*DeleteOptimizationResponse, error)

	// GetOptimizationWithResponse request
	GetOptimizationWithResponse(ctx context.Context, id openapi_types.UUID, reqEditors ...RequestEditorFn) (*GetOptimizationResponse, error)

	// GetUsageWithResponse request
	GetUsageWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetUsageResponse, error)

	// GetWebhookSecretWithResponse request
	GetWebhookSecretWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetWebhookSecretResponse, error)
}

ClientWithResponsesInterface is the interface specification for the client with responses above.

type CreateApiKeyJSONRequestBody

type CreateApiKeyJSONRequestBody = CreateApiKeyRequest

CreateApiKeyJSONRequestBody defines body for CreateApiKey for application/json ContentType.

type CreateApiKeyRequest

type CreateApiKeyRequest struct {
	// Name A human-readable label for this API key
	Name string `json:"name"`
}

CreateApiKeyRequest defines model for CreateApiKeyRequest.

type CreateApiKeyResponse

type CreateApiKeyResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON201      *struct {
		Data    ApiKeyCreated `json:"data"`
		Success bool          `json:"success"`
	}
	JSON401 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseCreateApiKeyResponse

func ParseCreateApiKeyResponse(rsp *http.Response) (*CreateApiKeyResponse, error)

ParseCreateApiKeyResponse parses an HTTP response from a CreateApiKeyWithResponse call

func (CreateApiKeyResponse) Status

func (r CreateApiKeyResponse) Status() string

Status returns HTTPResponse.Status

func (CreateApiKeyResponse) StatusCode

func (r CreateApiKeyResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type CreateOptimizationJSONRequestBody

type CreateOptimizationJSONRequestBody = CreateOptimizationRequest

CreateOptimizationJSONRequestBody defines body for CreateOptimization for application/json ContentType.

type CreateOptimizationRequest

type CreateOptimizationRequest struct {
	// Addresses List of addresses to optimize (minimum 3)
	Addresses []Address `json:"addresses"`

	// Geocoding How addresses sent without coordinates are geocoded. The geocoder has no country or bounds parameter of its own, so this is the only way to rule out a homonym elsewhere.
	Geocoding *GeocodingOptions `json:"geocoding,omitempty"`

	// Parameters Optional optimization parameters
	Parameters *OptimizationParameters `json:"parameters,omitempty"`

	// WebhookUrl Public https URL to receive an HMAC-signed webhook when the optimization completes or fails. Plain http, an IP address instead of a host name, localhost and names that resolve to private-network addresses are refused, and redirects are not followed; for local development, expose your server with a tunnel such as ngrok and pass its https URL.
	WebhookUrl *string `json:"webhookUrl,omitempty"`
}

CreateOptimizationRequest defines model for CreateOptimizationRequest.

type CreateOptimizationResponse

type CreateOptimizationResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON202      *struct {
		Data    Optimization `json:"data"`
		Success bool         `json:"success"`
	}
	JSON400 *ErrorResponse
	JSON401 *ErrorResponse
	JSON402 *ErrorResponse
	JSON422 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseCreateOptimizationResponse

func ParseCreateOptimizationResponse(rsp *http.Response) (*CreateOptimizationResponse, error)

ParseCreateOptimizationResponse parses an HTTP response from a CreateOptimizationWithResponse call

func (CreateOptimizationResponse) Status

Status returns HTTPResponse.Status

func (CreateOptimizationResponse) StatusCode

func (r CreateOptimizationResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type DeleteOptimizationResponse

type DeleteOptimizationResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *DeletedResource
	JSON401      *ErrorResponse
	JSON404      *ErrorResponse
	JSON429      *ErrorResponse
}

func ParseDeleteOptimizationResponse

func ParseDeleteOptimizationResponse(rsp *http.Response) (*DeleteOptimizationResponse, error)

ParseDeleteOptimizationResponse parses an HTTP response from a DeleteOptimizationWithResponse call

func (DeleteOptimizationResponse) Status

Status returns HTTPResponse.Status

func (DeleteOptimizationResponse) StatusCode

func (r DeleteOptimizationResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type DeletedResource

type DeletedResource struct {
	Data struct {
		// Id Id of the deleted resource
		Id openapi_types.UUID `json:"id"`
	} `json:"data"`
	Success bool `json:"success"`
}

DeletedResource defines model for DeletedResource.

type ErrorResponse

type ErrorResponse struct {
	Error struct {
		// Code Machine-readable error code
		Code string `json:"code"`

		// Details Optional machine-readable context. The message stands alone without it. CONCURRENCY_LIMIT_EXCEEDED carries `active`, `limit` and `activeOptimizationIds`; GEOCODING_UNRESOLVED carries `unresolved` (each with `index`, `address`, `reason` of not_found / ambiguous / imprecise, and `candidates`), `resolved` (the stops that did geocode, each with `index`, `address`, `lat`, `lng` and the matched place — paid for, so resend them as coordinates) and `geocodingPriceMicros`.
		Details *map[string]interface{} `json:"details,omitempty"`

		// Message Human-readable error message
		Message string `json:"message"`
	} `json:"error"`
	Success bool `json:"success"`
}

ErrorResponse defines model for ErrorResponse.

type ForwardGeocodeJSONRequestBody

type ForwardGeocodeJSONRequestBody = ForwardGeocodeRequest

ForwardGeocodeJSONRequestBody defines body for ForwardGeocode for application/json ContentType.

type ForwardGeocodeRequest

type ForwardGeocodeRequest struct {
	// Address Address string to geocode
	Address string `json:"address"`

	// Detailed Return detailed result fields
	Detailed *bool `json:"detailed,omitempty"`

	// Nocache Bypass geocoding cache
	Nocache *bool `json:"nocache,omitempty"`
}

ForwardGeocodeRequest defines model for ForwardGeocodeRequest.

type ForwardGeocodeResponse

type ForwardGeocodeResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data struct {
			// PriceMicros What this request cost, in micro-dollars (1 USD = 1 000 000)
			PriceMicros int `json:"priceMicros"`

			// Result One result per distinct address sent. `ok` carries the single match inline (`address`, `lat`, `lng`, `precision`, `confidence`); `ambiguous` carries the matches in `candidates` and nothing inline; `not_found` carries only `original`.
			Result GeocodeResult `json:"result"`
		} `json:"data"`
		Success bool `json:"success"`
	}
	JSON400 *ErrorResponse
	JSON401 *ErrorResponse
	JSON402 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseForwardGeocodeResponse

func ParseForwardGeocodeResponse(rsp *http.Response) (*ForwardGeocodeResponse, error)

ParseForwardGeocodeResponse parses an HTTP response from a ForwardGeocodeWithResponse call

func (ForwardGeocodeResponse) Status

func (r ForwardGeocodeResponse) Status() string

Status returns HTTPResponse.Status

func (ForwardGeocodeResponse) StatusCode

func (r ForwardGeocodeResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type ForwardGeocoding added in v1.4.0

type ForwardGeocoding struct {
	PriceMicros int
	Result      GeocodeResult
}

ForwardGeocoding is the answer to ForwardGeocode.

type GeocodeCandidate

type GeocodeCandidate struct {
	// Address The normalized address the geocoder matched
	Address string `json:"address"`

	// Confidence The geocoder's own confidence label, e.g. `high` or `medium`
	Confidence *string `json:"confidence"`

	// Lat Latitude
	Lat float64 `json:"lat"`

	// Lng Longitude
	Lng float64 `json:"lng"`

	// Precision How exact the match is. `address` is a specific place you can drive to (a street address, building or point of interest); `street` is a road without a number, `area` a neighborhood or postal code, `city` a town, `region` a state or country. Only `address` should be routed to without asking.
	Precision GeocodeCandidatePrecision `json:"precision"`
}

GeocodeCandidate defines model for GeocodeCandidate.

type GeocodeCandidatePrecision

type GeocodeCandidatePrecision string

GeocodeCandidatePrecision How exact the match is. `address` is a specific place you can drive to (a street address, building or point of interest); `street` is a road without a number, `area` a neighborhood or postal code, `city` a town, `region` a state or country. Only `address` should be routed to without asking.

const (
	GeocodeCandidatePrecisionAddress GeocodeCandidatePrecision = "address"
	GeocodeCandidatePrecisionArea    GeocodeCandidatePrecision = "area"
	GeocodeCandidatePrecisionCity    GeocodeCandidatePrecision = "city"
	GeocodeCandidatePrecisionOther   GeocodeCandidatePrecision = "other"
	GeocodeCandidatePrecisionRegion  GeocodeCandidatePrecision = "region"
	GeocodeCandidatePrecisionStreet  GeocodeCandidatePrecision = "street"
)

Defines values for GeocodeCandidatePrecision.

type GeocodeResult

type GeocodeResult struct {
	// Address The normalized address (status `ok` only)
	Address *string `json:"address,omitempty"`

	// Candidates Every place that fits (status `ambiguous` only)
	Candidates *[]GeocodeCandidate `json:"candidates,omitempty"`

	// Confidence The geocoder's own confidence label (status `ok` only)
	Confidence *string `json:"confidence"`

	// Lat Latitude (status `ok` only)
	Lat *float64 `json:"lat,omitempty"`

	// Lng Longitude (status `ok` only)
	Lng *float64 `json:"lng,omitempty"`

	// Original The address string exactly as sent. Match results to your own data by this field, never by position.
	Original string `json:"original"`

	// Precision How exact the match is (status `ok` only); only `address` is exact enough to drive to
	Precision *GeocodeResultPrecision `json:"precision,omitempty"`

	// Status `ok`: one match. `ambiguous`: several places fit (e.g. a bare "Springfield"); see `candidates`, or add a city/state to the input and retry. `not_found`: the geocoder could not place the string.
	Status GeocodeResultStatus `json:"status"`
}

GeocodeResult One result per distinct address sent. `ok` carries the single match inline (`address`, `lat`, `lng`, `precision`, `confidence`); `ambiguous` carries the matches in `candidates` and nothing inline; `not_found` carries only `original`.

type GeocodeResultPrecision

type GeocodeResultPrecision string

GeocodeResultPrecision How exact the match is (status `ok` only); only `address` is exact enough to drive to

const (
	GeocodeResultPrecisionAddress GeocodeResultPrecision = "address"
	GeocodeResultPrecisionArea    GeocodeResultPrecision = "area"
	GeocodeResultPrecisionCity    GeocodeResultPrecision = "city"
	GeocodeResultPrecisionOther   GeocodeResultPrecision = "other"
	GeocodeResultPrecisionRegion  GeocodeResultPrecision = "region"
	GeocodeResultPrecisionStreet  GeocodeResultPrecision = "street"
)

Defines values for GeocodeResultPrecision.

type GeocodeResultStatus

type GeocodeResultStatus string

GeocodeResultStatus `ok`: one match. `ambiguous`: several places fit (e.g. a bare "Springfield"); see `candidates`, or add a city/state to the input and retry. `not_found`: the geocoder could not place the string.

const (
	Ambiguous GeocodeResultStatus = "ambiguous"
	NotFound  GeocodeResultStatus = "not_found"
	Ok        GeocodeResultStatus = "ok"
)

Defines values for GeocodeResultStatus.

type GeocodingOptions

type GeocodingOptions struct {
	// Bounds Bounding box; geocoding candidates outside it are discarded before anything else.
	Bounds *struct {
		East  float64 `json:"east"`
		North float64 `json:"north"`
		South float64 `json:"south"`
		West  float64 `json:"west"`
	} `json:"bounds,omitempty"`

	// MinPrecision Coarsest match still accepted. Default `address`: a street address, building or point of interest. `street` also accepts a road without a number; `city` accepts a town centre.
	MinPrecision *GeocodingOptionsMinPrecision `json:"minPrecision,omitempty"`

	// Region Appended to every address that needs geocoding, e.g. "Springfield, MO" or "Berlin, Germany". The cheapest way to rule out homonyms elsewhere.
	Region *string `json:"region,omitempty"`
}

GeocodingOptions How addresses sent without coordinates are geocoded. The geocoder has no country or bounds parameter of its own, so this is the only way to rule out a homonym elsewhere.

type GeocodingOptionsMinPrecision

type GeocodingOptionsMinPrecision string

GeocodingOptionsMinPrecision Coarsest match still accepted. Default `address`: a street address, building or point of interest. `street` also accepts a road without a number; `city` accepts a town centre.

const (
	GeocodingOptionsMinPrecisionAddress GeocodingOptionsMinPrecision = "address"
	GeocodingOptionsMinPrecisionArea    GeocodingOptionsMinPrecision = "area"
	GeocodingOptionsMinPrecisionCity    GeocodingOptionsMinPrecision = "city"
	GeocodingOptionsMinPrecisionOther   GeocodingOptionsMinPrecision = "other"
	GeocodingOptionsMinPrecisionRegion  GeocodingOptionsMinPrecision = "region"
	GeocodingOptionsMinPrecisionStreet  GeocodingOptionsMinPrecision = "street"
)

Defines values for GeocodingOptionsMinPrecision.

type GetAccountResponse

type GetAccountResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data    Account `json:"data"`
		Success bool    `json:"success"`
	}
	JSON401 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseGetAccountResponse

func ParseGetAccountResponse(rsp *http.Response) (*GetAccountResponse, error)

ParseGetAccountResponse parses an HTTP response from a GetAccountWithResponse call

func (GetAccountResponse) Status

func (r GetAccountResponse) Status() string

Status returns HTTPResponse.Status

func (GetAccountResponse) StatusCode

func (r GetAccountResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type GetOptimizationResponse

type GetOptimizationResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data    Optimization `json:"data"`
		Success bool         `json:"success"`
	}
	JSON401 *ErrorResponse
	JSON404 *ErrorResponse
	JSON409 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseGetOptimizationResponse

func ParseGetOptimizationResponse(rsp *http.Response) (*GetOptimizationResponse, error)

ParseGetOptimizationResponse parses an HTTP response from a GetOptimizationWithResponse call

func (GetOptimizationResponse) Status

func (r GetOptimizationResponse) Status() string

Status returns HTTPResponse.Status

func (GetOptimizationResponse) StatusCode

func (r GetOptimizationResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type GetUsageResponse

type GetUsageResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data    Usage `json:"data"`
		Success bool  `json:"success"`
	}
	JSON401 *ErrorResponse
}

func ParseGetUsageResponse

func ParseGetUsageResponse(rsp *http.Response) (*GetUsageResponse, error)

ParseGetUsageResponse parses an HTTP response from a GetUsageWithResponse call

func (GetUsageResponse) Status

func (r GetUsageResponse) Status() string

Status returns HTTPResponse.Status

func (GetUsageResponse) StatusCode

func (r GetUsageResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type GetWebhookSecretResponse added in v1.3.6

type GetWebhookSecretResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data struct {
			Previous WebhookSecret `json:"previous"`
			Primary  WebhookSecret `json:"primary"`
		} `json:"data"`
		Success bool `json:"success"`
	}
	JSON401 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseGetWebhookSecretResponse added in v1.3.6

func ParseGetWebhookSecretResponse(rsp *http.Response) (*GetWebhookSecretResponse, error)

ParseGetWebhookSecretResponse parses an HTTP response from a GetWebhookSecretWithResponse call

func (GetWebhookSecretResponse) Status added in v1.3.6

func (r GetWebhookSecretResponse) Status() string

Status returns HTTPResponse.Status

func (GetWebhookSecretResponse) StatusCode added in v1.3.6

func (r GetWebhookSecretResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type HttpRequestDoer

type HttpRequestDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer performs HTTP requests.

The standard http.Client implements this interface.

type ListApiKeysResponse

type ListApiKeysResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data    []ApiKey `json:"data"`
		Success bool     `json:"success"`
	}
	JSON401 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseListApiKeysResponse

func ParseListApiKeysResponse(rsp *http.Response) (*ListApiKeysResponse, error)

ParseListApiKeysResponse parses an HTTP response from a ListApiKeysWithResponse call

func (ListApiKeysResponse) Status

func (r ListApiKeysResponse) Status() string

Status returns HTTPResponse.Status

func (ListApiKeysResponse) StatusCode

func (r ListApiKeysResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type ListOptimizationsParams

type ListOptimizationsParams struct {
	// Cursor Cursor for pagination (optimization ID). Results after this ID will be returned.
	Cursor *openapi_types.UUID `form:"cursor,omitempty" json:"cursor,omitempty"`

	// Limit Maximum number of results to return
	Limit *int `form:"limit,omitempty" json:"limit,omitempty"`

	// Status Filter by optimization status
	Status *ListOptimizationsParamsStatus `form:"status,omitempty" json:"status,omitempty"`
}

ListOptimizationsParams defines parameters for ListOptimizations.

type ListOptimizationsParamsStatus

type ListOptimizationsParamsStatus string

ListOptimizationsParamsStatus defines parameters for ListOptimizations.

const (
	Completed  ListOptimizationsParamsStatus = "completed"
	Failed     ListOptimizationsParamsStatus = "failed"
	Pending    ListOptimizationsParamsStatus = "pending"
	Processing ListOptimizationsParamsStatus = "processing"
)

Defines values for ListOptimizationsParamsStatus.

type ListOptimizationsResponse

type ListOptimizationsResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data struct {
			Items []Optimization `json:"items"`

			// NextCursor Cursor for the next page. Null if no more results.
			NextCursor *openapi_types.UUID `json:"nextCursor"`
		} `json:"data"`
		Success bool `json:"success"`
	}
	JSON401 *ErrorResponse
	JSON429 *ErrorResponse
}

func ParseListOptimizationsResponse

func ParseListOptimizationsResponse(rsp *http.Response) (*ListOptimizationsResponse, error)

ParseListOptimizationsResponse parses an HTTP response from a ListOptimizationsWithResponse call

func (ListOptimizationsResponse) Status

func (r ListOptimizationsResponse) Status() string

Status returns HTTPResponse.Status

func (ListOptimizationsResponse) StatusCode

func (r ListOptimizationsResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type MppChallenge

type MppChallenge struct {
	AmountCents  int                  `json:"amountCents"`
	BonusPercent *int                 `json:"bonusPercent,omitempty"`
	Currency     MppChallengeCurrency `json:"currency"`

	// Endpoint Where to fulfill the payment
	Endpoint string `json:"endpoint"`

	// GrantMicros What the balance gains for this amount, in micro-dollars (incl. volume bonus)
	GrantMicros int `json:"grantMicros"`

	// MinCents Smallest acceptable pack
	MinCents int                `json:"minCents"`
	Scheme   MppChallengeScheme `json:"scheme"`
	Status   MppChallengeStatus `json:"status"`
}

MppChallenge defines model for MppChallenge.

type MppChallengeCurrency

type MppChallengeCurrency string

MppChallengeCurrency defines model for MppChallenge.Currency.

const (
	Usd MppChallengeCurrency = "usd"
)

Defines values for MppChallengeCurrency.

type MppChallengeScheme

type MppChallengeScheme string

MppChallengeScheme defines model for MppChallenge.Scheme.

const (
	Mpp MppChallengeScheme = "mpp"
)

Defines values for MppChallengeScheme.

type MppChallengeStatus

type MppChallengeStatus string

MppChallengeStatus defines model for MppChallenge.Status.

const (
	PaymentRequired MppChallengeStatus = "payment_required"
)

Defines values for MppChallengeStatus.

type OnBusy

type OnBusy func(BusyEvent) BusyDecision

OnBusy is called on every busy answer, synchronously: decide, and the SDK does the waiting (honouring Retry-After and polling a named optimization first, so a slot whose deadline passed is released server-side). Do not sleep here. Without a callback the SDK waits until BusyTimeout, then fails.

type Optimization

type Optimization struct {
	// Addresses The stops, with coordinates settled (geocoded ones carry `resolved`)
	Addresses *[]OptimizationAddress `json:"addresses,omitempty"`

	// CreatedAt Creation timestamp
	CreatedAt time.Time `json:"createdAt"`

	// ErrorMessage Error details (available when status is `failed`)
	ErrorMessage *string `json:"errorMessage"`

	// GeocodingPriceMicros On the create response only, when addresses were geocoded as part of the request: what that lookup cost, in micro-dollars, charged separately
	GeocodingPriceMicros *int               `json:"geocodingPriceMicros,omitempty"`
	Id                   openapi_types.UUID `json:"id"`

	// Parameters Optional optimization parameters
	Parameters *OptimizationParameters `json:"parameters,omitempty"`

	// PriceMicros What this optimization cost, in micro-dollars (1 USD = 1 000 000)
	PriceMicros int `json:"priceMicros"`

	// Result Optimization result (available when status is `completed`). `routes` always holds at least one route — a single-vehicle run is an array of one. `unroutedStops` is always present too — **always check it**: a stop listed there is not in the plan at all.
	Result *OptimizationResult `json:"result,omitempty"`
	Status OptimizationStatus  `json:"status"`

	// UpdatedAt Last update timestamp
	UpdatedAt time.Time `json:"updatedAt"`

	// WebhookStatus Webhook delivery status
	WebhookStatus *OptimizationWebhookStatus `json:"webhookStatus"`

	// WebhookUrl Configured webhook URL
	WebhookUrl *string `json:"webhookUrl"`
}

Optimization defines model for Optimization.

type OptimizationAddress

type OptimizationAddress struct {
	// Address The stop's address. With `lat`/`lng` it is only a label; without them it is geocoded (charged at the geocode price) and must resolve to exactly one place.
	Address string `json:"address"`

	// IsDepot When true, marks this stop as the route's depot (start and/or end).
	IsDepot *bool   `json:"isDepot,omitempty"`
	Lat     float64 `json:"lat"`
	Lng     float64 `json:"lng"`

	// Priority Stop priority (1 = highest). Higher-priority stops are scheduled earlier.
	Priority *int `json:"priority,omitempty"`

	// Resolved Present when the coordinates came from geocoding: the place that was matched.
	Resolved *struct {
		Address    string                               `json:"address"`
		Confidence *string                              `json:"confidence,omitempty"`
		Precision  OptimizationAddressResolvedPrecision `json:"precision"`
	} `json:"resolved,omitempty"`

	// ServiceTimeSeconds Time spent at this stop, in seconds (service dwell time).
	ServiceTimeSeconds *int `json:"serviceTimeSeconds,omitempty"`

	// TimeWindowEnd Latest local time this stop can be served, HH:MM. The stop's `serviceTimeSeconds` must finish by then, not merely begin.
	TimeWindowEnd *string `json:"timeWindowEnd,omitempty"`

	// TimeWindowStart Earliest local time this stop can be served, HH:MM. Taken as the first such time at or after the route starts, so 02:00 on a route leaving at 22:00 means the following morning.
	TimeWindowStart *string `json:"timeWindowStart,omitempty"`
}

OptimizationAddress A stop as the optimization stored it: coordinates always present. `resolved` is set on a stop whose coordinates came from geocoding.

type OptimizationAddressResolvedPrecision

type OptimizationAddressResolvedPrecision string

OptimizationAddressResolvedPrecision defines model for OptimizationAddress.Resolved.Precision.

const (
	OptimizationAddressResolvedPrecisionAddress OptimizationAddressResolvedPrecision = "address"
	OptimizationAddressResolvedPrecisionArea    OptimizationAddressResolvedPrecision = "area"
	OptimizationAddressResolvedPrecisionCity    OptimizationAddressResolvedPrecision = "city"
	OptimizationAddressResolvedPrecisionOther   OptimizationAddressResolvedPrecision = "other"
	OptimizationAddressResolvedPrecisionRegion  OptimizationAddressResolvedPrecision = "region"
	OptimizationAddressResolvedPrecisionStreet  OptimizationAddressResolvedPrecision = "street"
)

Defines values for OptimizationAddressResolvedPrecision.

type OptimizationFailedError

type OptimizationFailedError struct {
	Optimization Optimization
}

OptimizationFailedError means the optimization finished, but the solver could not produce a plan.

func (*OptimizationFailedError) Error

func (e *OptimizationFailedError) Error() string

type OptimizationPage added in v1.4.0

type OptimizationPage struct {
	Items []Optimization
	// NextCursor is the cursor for the next page; nil on the last one.
	NextCursor *openapi_types.UUID
}

OptimizationPage is one page of ListOptimizations.

type OptimizationParameters

type OptimizationParameters struct {
	// MaxRouteDistanceMeters Maximum distance of one route, in meters. Applied in steps of 1609 meters, rounded down, so a cap under 1609 becomes 1609. Availability and ceiling depend on your plan.
	MaxRouteDistanceMeters *int `json:"maxRouteDistanceMeters,omitempty"`

	// MaxRouteDurationSeconds Maximum wall-clock duration of one route, in seconds. Availability and ceiling depend on your plan.
	MaxRouteDurationSeconds *int `json:"maxRouteDurationSeconds,omitempty"`

	// MaxRoutes Maximum number of vehicles (routes) for multi-route VRP optimization. Availability and ceiling depend on your plan.
	MaxRoutes *int `json:"maxRoutes,omitempty"`

	// OptimizeMode Optimization objective: minimize total travel time or distance.
	OptimizeMode *OptimizationParametersOptimizeMode `json:"optimizeMode,omitempty"`

	// RoundTrip When true, the route returns to the starting depot after the last stop.
	RoundTrip *bool `json:"roundTrip,omitempty"`

	// RouteStartAt When the route starts, as local date and time without a zone, e.g. 2026-04-14T08:00. Read in `timezone`.
	RouteStartAt *string `json:"routeStartAt,omitempty"`

	// Timezone IANA timezone the local times in this request are read in, for example America/New_York. Required when any stop has a delivery window.
	Timezone *string `json:"timezone,omitempty"`

	// TravelMode Mode of transportation used when computing the route.
	TravelMode *OptimizationParametersTravelMode `json:"travelMode,omitempty"`
}

OptimizationParameters Optional optimization parameters

type OptimizationParametersOptimizeMode

type OptimizationParametersOptimizeMode string

OptimizationParametersOptimizeMode Optimization objective: minimize total travel time or distance.

const (
	Distance OptimizationParametersOptimizeMode = "Distance"
	Time     OptimizationParametersOptimizeMode = "Time"
)

Defines values for OptimizationParametersOptimizeMode.

type OptimizationParametersTravelMode

type OptimizationParametersTravelMode string

OptimizationParametersTravelMode Mode of transportation used when computing the route.

const (
	Bicycling OptimizationParametersTravelMode = "bicycling"
	Driving   OptimizationParametersTravelMode = "driving"
	Walking   OptimizationParametersTravelMode = "walking"
)

Defines values for OptimizationParametersTravelMode.

type OptimizationResult

type OptimizationResult struct {
	// Routes One entry per vehicle, in no particular order.
	Routes []Route `json:"routes"`

	// UnroutedStops Stops the solver could not place in any route — most often because no route could reach them inside their delivery window. They are NOT scheduled. Always present, empty when everything fit, so it cannot be missed by only appearing on failure. Whether a window is reachable depends on every other stop, so this can only be known after solving.
	UnroutedStops []struct {
		// Index Position of the stop in the request's `addresses` array
		Index int `json:"index"`
	} `json:"unroutedStops"`
}

OptimizationResult Optimization result (available when status is `completed`). `routes` always holds at least one route — a single-vehicle run is an array of one. `unroutedStops` is always present too — **always check it**: a stop listed there is not in the plan at all.

type OptimizationStatus

type OptimizationStatus string

OptimizationStatus defines model for Optimization.Status.

const (
	OptimizationStatusCompleted  OptimizationStatus = "completed"
	OptimizationStatusFailed     OptimizationStatus = "failed"
	OptimizationStatusPending    OptimizationStatus = "pending"
	OptimizationStatusProcessing OptimizationStatus = "processing"
)

Defines values for OptimizationStatus.

type OptimizationTimeoutError

type OptimizationTimeoutError struct {
	OptimizationID openapi_types.UUID
	Timeout        time.Duration
}

OptimizationTimeoutError means the wait ran out of time. The optimization is still running server-side.

func (*OptimizationTimeoutError) Error

func (e *OptimizationTimeoutError) Error() string

type OptimizationWebhookStatus

type OptimizationWebhookStatus string

OptimizationWebhookStatus Webhook delivery status

const (
	OptimizationWebhookStatusDelivered OptimizationWebhookStatus = "delivered"
	OptimizationWebhookStatusFailed    OptimizationWebhookStatus = "failed"
	OptimizationWebhookStatusPending   OptimizationWebhookStatus = "pending"
)

Defines values for OptimizationWebhookStatus.

type ParamLimit

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

ParamLimit "unavailable" when the plan does not offer the parameter, otherwise the largest value it accepts

func (ParamLimit) AsParamLimit0

func (t ParamLimit) AsParamLimit0() (ParamLimit0, error)

AsParamLimit0 returns the union data inside the ParamLimit as a ParamLimit0

func (ParamLimit) AsParamLimit1

func (t ParamLimit) AsParamLimit1() (ParamLimit1, error)

AsParamLimit1 returns the union data inside the ParamLimit as a ParamLimit1

func (*ParamLimit) FromParamLimit0

func (t *ParamLimit) FromParamLimit0(v ParamLimit0) error

FromParamLimit0 overwrites any union data inside the ParamLimit as the provided ParamLimit0

func (*ParamLimit) FromParamLimit1

func (t *ParamLimit) FromParamLimit1(v ParamLimit1) error

FromParamLimit1 overwrites any union data inside the ParamLimit as the provided ParamLimit1

func (ParamLimit) MarshalJSON

func (t ParamLimit) MarshalJSON() ([]byte, error)

func (*ParamLimit) MergeParamLimit0

func (t *ParamLimit) MergeParamLimit0(v ParamLimit0) error

MergeParamLimit0 performs a merge with any union data inside the ParamLimit, using the provided ParamLimit0

func (*ParamLimit) MergeParamLimit1

func (t *ParamLimit) MergeParamLimit1(v ParamLimit1) error

MergeParamLimit1 performs a merge with any union data inside the ParamLimit, using the provided ParamLimit1

func (*ParamLimit) UnmarshalJSON

func (t *ParamLimit) UnmarshalJSON(b []byte) error

type ParamLimit0

type ParamLimit0 string

ParamLimit0 defines model for ParamLimit.0.

const (
	Unavailable ParamLimit0 = "unavailable"
)

Defines values for ParamLimit0.

type ParamLimit1

type ParamLimit1 = int

ParamLimit1 defines model for .

type RequestEditorFn

type RequestEditorFn func(ctx context.Context, req *http.Request) error

RequestEditorFn is the function signature for the RequestEditor callback function

type RevokeApiKeyResponse

type RevokeApiKeyResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *DeletedResource
	JSON401      *ErrorResponse
	JSON404      *ErrorResponse
	JSON429      *ErrorResponse
}

func ParseRevokeApiKeyResponse

func ParseRevokeApiKeyResponse(rsp *http.Response) (*RevokeApiKeyResponse, error)

ParseRevokeApiKeyResponse parses an HTTP response from a RevokeApiKeyWithResponse call

func (RevokeApiKeyResponse) Status

func (r RevokeApiKeyResponse) Status() string

Status returns HTTPResponse.Status

func (RevokeApiKeyResponse) StatusCode

func (r RevokeApiKeyResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type Route

type Route struct {
	// Polyline Encoded polyline for the whole route
	Polyline *string `json:"polyline,omitempty"`

	// RouteStartAt When the route starts, as an ISO timestamp in the request's `timezone`. Absent when the request gave neither `routeStartAt` nor `timezone`, since there is then no clock to report against.
	RouteStartAt *string `json:"routeStartAt,omitempty"`

	// TotalDistanceMeters Total route distance, in meters
	TotalDistanceMeters int `json:"totalDistanceMeters"`

	// TotalTimeSeconds Total route duration, in seconds
	TotalTimeSeconds int `json:"totalTimeSeconds"`

	// Waypoints Stops in the order they should be driven. `index` refers back to the position of that stop in the request's `addresses` array.
	Waypoints []struct {
		// ArrivalAt ISO timestamp of arrival, in the request's `timezone`. Absent when the request set no route start.
		ArrivalAt *string `json:"arrivalAt,omitempty"`

		// CumulativeDistanceMeters Distance travelled up to this stop, in meters
		CumulativeDistanceMeters int `json:"cumulativeDistanceMeters"`

		// CumulativeTimeSeconds Seconds elapsed up to this stop, including service time at earlier stops
		CumulativeTimeSeconds int `json:"cumulativeTimeSeconds"`

		// DepartureAt ISO timestamp of departure — arrival plus the stop's `serviceTimeSeconds`. Absent when the request set no route start.
		DepartureAt *string `json:"departureAt,omitempty"`

		// Index Position of this stop in the request's `addresses` array
		Index int `json:"index"`

		// PolylineToNext Encoded polyline from this stop to the next one; null at the last stop
		PolylineToNext *string `json:"polylineToNext"`

		// WaitTimeSeconds Seconds spent waiting at this stop for its delivery window to open. Zero when the driver arrives inside the window, or when the stop has none.
		WaitTimeSeconds int `json:"waitTimeSeconds"`
	} `json:"waypoints"`
}

Route One optimized vehicle route. Distances are in meters and durations in seconds — the API takes and reports SI units, and carries no unit switch. Times of day are ISO timestamps in the request's `timezone`.

type TopupCreditsJSONBody

type TopupCreditsJSONBody struct {
	// AmountCents Top-up amount in cents (defaults to the minimum pack).
	AmountCents *int `json:"amountCents,omitempty"`

	// SandboxPaymentId Sandbox-only synthetic payment id to fulfill immediately.
	SandboxPaymentId *string `json:"sandboxPaymentId,omitempty"`
}

TopupCreditsJSONBody defines parameters for TopupCredits.

type TopupCreditsJSONRequestBody

type TopupCreditsJSONRequestBody TopupCreditsJSONBody

TopupCreditsJSONRequestBody defines body for TopupCredits for application/json ContentType.

type TopupCreditsResponse

type TopupCreditsResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *struct {
		Data    TopupReceipt `json:"data"`
		Success bool         `json:"success"`
	}
	JSON401 *ErrorResponse
	JSON402 *struct {
		Challenge *MppChallenge `json:"challenge,omitempty"`
		Error     *struct {
			Code    *string `json:"code,omitempty"`
			Message *string `json:"message,omitempty"`
		} `json:"error,omitempty"`
		Success *bool `json:"success,omitempty"`
	}
	JSON501 *ErrorResponse
}

func ParseTopupCreditsResponse

func ParseTopupCreditsResponse(rsp *http.Response) (*TopupCreditsResponse, error)

ParseTopupCreditsResponse parses an HTTP response from a TopupCreditsWithResponse call

func (TopupCreditsResponse) Status

func (r TopupCreditsResponse) Status() string

Status returns HTTPResponse.Status

func (TopupCreditsResponse) StatusCode

func (r TopupCreditsResponse) StatusCode() int

StatusCode returns HTTPResponse.StatusCode

type TopupReceipt

type TopupReceipt struct {
	AmountCents int `json:"amountCents"`

	// Balance New balance, or null if this was a duplicate
	Balance     *int   `json:"balance"`
	Duplicate   bool   `json:"duplicate"`
	GrantMicros int    `json:"grantMicros"`
	PaymentId   string `json:"paymentId"`
}

TopupReceipt defines model for TopupReceipt.

type Usage

type Usage struct {
	// BalanceMicros Current prepaid balance in micro-dollars (1 USD = 1 000 000). Integer, exact: the ledger always sums to it.
	BalanceMicros int           `json:"balanceMicros"`
	Currency      UsageCurrency `json:"currency"`

	// Ledger Recent movements, newest first
	Ledger []struct {
		// AmountMicros Signed change in micro-dollars (negative for usage)
		AmountMicros int                `json:"amountMicros"`
		CreatedAt    time.Time          `json:"createdAt"`
		Id           openapi_types.UUID `json:"id"`

		// Kind What was billed (usage/refund rows only)
		Kind *UsageLedgerKind `json:"kind"`

		// Quantity Billable unit count, e.g. address count
		Quantity *int              `json:"quantity"`
		Reason   UsageLedgerReason `json:"reason"`

		// RefId Linked object id, e.g. the optimization id
		RefId *string `json:"refId"`
	} `json:"ledger"`
}

Usage defines model for Usage.

type UsageCurrency

type UsageCurrency string

UsageCurrency defines model for Usage.Currency.

const (
	UsageCurrencyUSD UsageCurrency = "USD"
)

Defines values for UsageCurrency.

type UsageLedgerKind

type UsageLedgerKind string

UsageLedgerKind What was billed (usage/refund rows only)

const (
	UsageLedgerKindGeocode      UsageLedgerKind = "geocode"
	UsageLedgerKindOptimization UsageLedgerKind = "optimization"
)

Defines values for UsageLedgerKind.

type UsageLedgerReason

type UsageLedgerReason string

UsageLedgerReason defines model for Usage.Ledger.Reason.

const (
	UsageLedgerReasonAdjustment UsageLedgerReason = "adjustment"
	UsageLedgerReasonGrant      UsageLedgerReason = "grant"
	UsageLedgerReasonRefund     UsageLedgerReason = "refund"
	UsageLedgerReasonTopup      UsageLedgerReason = "topup"
	UsageLedgerReasonUsage      UsageLedgerReason = "usage"
)

Defines values for UsageLedgerReason.

type WaitOptions

type WaitOptions struct {
	Timeout      time.Duration
	InitialDelay time.Duration
	MaxDelay     time.Duration
	OnBusy       OnBusy
	BusyTimeout  time.Duration
}

WaitOptions tunes how long and how eagerly to poll, and how busy answers are handled. The zero value is usable: every field falls back to its Default* constant, and a nil OnBusy waits until BusyTimeout, then fails.

type WebhookError

type WebhookError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

WebhookError says why an optimization failed. Code is NO_ROUTES (the engine produced no routes), PROCESSING_FAILED (the job threw) or TIMED_OUT (it did not finish within 15 minutes and its concurrency slot was released); the the charge is refunded in every case. More codes may be added, so handle the ones you know and fall through on the rest.

type WebhookEvent

type WebhookEvent struct {
	Type           string              `json:"type"`
	OptimizationID string              `json:"optimizationId"`
	Result         *OptimizationResult `json:"result,omitempty"`
	Error          *WebhookError       `json:"error,omitempty"`
}

WebhookEvent is the body we POST to your WebhookUrl.

Go has no sum types, so the two outcomes share one struct and Type says which you have: Result is non-nil on EventOptimizationCompleted, Error is non-nil on EventOptimizationFailed. Switch on Type rather than nil-checking the fields — an added event would otherwise look like a completed one with nothing in it.

func VerifyWebhook

func VerifyWebhook(body []byte, signature, secret string) (*WebhookEvent, error)

VerifyWebhook verifies a delivery and returns its parsed body.

Pass the raw request body, exactly the bytes you received — not a struct you have already decoded and re-encoded. That is what was signed.

It returns ErrWebhookSignature on a mismatch rather than a bool, so an unverified payload cannot reach your handler by accident: a bool is easy to ignore, an error the compiler nags about is not.

func VerifyWebhookRequest

func VerifyWebhookRequest(r *http.Request, secret string) (*WebhookEvent, error)

VerifyWebhookRequest verifies a delivery straight from an *http.Request: it reads the raw body and finds the signature header itself, so neither the header name nor the read-before-parse rule is yours to remember.

event, err := r4m.VerifyWebhookRequest(r, os.Getenv("R4M_WEBHOOK_SECRET"))
if errors.Is(err, r4m.ErrWebhookSignature) {
        http.Error(w, "invalid signature", http.StatusUnauthorized)
        return
}

The body is consumed; read it yourself and call VerifyWebhook if you need the bytes afterwards.

type WebhookSecret added in v1.3.6

type WebhookSecret struct {
	CreatedAt *time.Time `json:"createdAt"`

	// Secret The signing secret (`whsec_…`)
	Secret string `json:"secret"`
}

WebhookSecret defines model for WebhookSecret.

type WebhookSecrets added in v1.4.0

type WebhookSecrets struct {
	Previous WebhookSecret
	Primary  WebhookSecret
}

WebhookSecrets holds the secrets webhook deliveries are signed with.

Jump to

Keyboard shortcuts

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