Documentation
¶
Overview ¶
Package rest provides a client for interacting with RESTful API services.
Package rest provides a client for interacting with RESTful API services.
Package rest provides a client for interacting with RESTful API services. It simplifies making HTTP requests to REST endpoints, handling authentication, token renewal, and response parsing.
Example ¶
Example provides a documented example of how API key authentication works. This is not a real test but serves as documentation for users.
// API key authentication is automatically handled by the library // You obtain your API key (key ID and secret) from the service provider // // 1. Load your API key into your application // 2. Create a context with your API key // ctx := context.Background() // ctx = apiKey.Use(ctx) // // 3. Use the context with any API call // result, err := Do(ctx, "User:get", "GET", nil) // // The library automatically: // - Adds the key ID to the request parameters // - Adds a timestamp and nonce for security // - Calculates a cryptographic signature // - Ensures the signature is the last parameter in the URL // // All of this happens behind the scenes when you use the API key context // with rest.Do(), rest.Apply(), or rest.As() functions.
Index ¶
- Variables
- func Apply(ctx context.Context, path, method string, param any, target any) error
- func As[T any](ctx context.Context, path, method string, param any) (T, error)
- func ResponseAs[T any](r *Response) (T, error)
- func SpotApply(ctx context.Context, client SpotClient, path, method string, param any, ...) error
- func SpotAs[T any](ctx context.Context, client SpotClient, path, method string, param any) (T, error)
- type ApiKey
- type ContextRequest
- type Error
- type HttpError
- type Param
- type Response
- func Do(ctx context.Context, path, method string, param any) (*Response, error)
- func SpotDo(ctx context.Context, client SpotClient, path, method string, param any) (*Response, error)
- func SpotUpload(ctx context.Context, client SpotClient, req, method string, param Param, ...) (*Response, error)
- func Upload(ctx context.Context, req, method string, param Param, f io.Reader, ...) (*Response, error)
- func (r *Response) Apply(v any) error
- func (r *Response) ApplyContext(ctx context.Context, v any) error
- func (r *Response) FullRaw() (map[string]any, error)
- func (r *Response) Get(v string) (any, error)
- func (r *Response) GetString(v string) (string, error)
- func (r *Response) OffsetGet(ctx context.Context, key string) (any, error)
- func (r *Response) ParseData()
- func (r *Response) Raw() (any, error)
- func (r *Response) ReadValue(ctx context.Context) (any, error)
- func (r *Response) Value() (any, error)
- func (r *Response) ValueContext(ctx context.Context) (any, error)
- type RouterType
- type SenderInterface
- type SpotClient
- type Time
- type Token
- type TokenSender
- type UploadInfo
- type UploadProgressFunc
- type UploadWriteHandler
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // Debug enables verbose logging of REST API requests and responses Debug = false // Scheme defines the URL scheme for API requests (http or https) Scheme = "https" // Host defines the default hostname for API requests Host = "www.atonline.com" )
var ( // ErrNoClientID is returned when token renewal is attempted without a client ID ErrNoClientID = errors.New("no client_id has been provided for token renewal") // ErrNoRefreshToken is returned when token renewal is attempted without a refresh token ErrNoRefreshToken = errors.New("no refresh token is available and access token has expired") )
var ErrLoginRequired = errors.New("login required")
ErrLoginRequired is returned when an API endpoint requires authentication but no valid token was provided.
var ErrUploadStalled = errors.New("upload stalled: transferred less than 150KB in 30 seconds")
var RestHttpClient = &http.Client{ Transport: RestHttpTransport, Timeout: 300 * time.Second, }
RestHttpClient is the default HTTP client used for all REST API requests. It uses RestHttpTransport and has a 5-minute overall timeout.
var RestHttpTransport = &http.Transport{ Proxy: http.ProxyFromEnvironment, MaxIdleConns: 100, MaxIdleConnsPerHost: 50, MaxConnsPerHost: 200, IdleConnTimeout: 90 * time.Second, ResponseHeaderTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 5 * time.Second, }
RestHttpTransport is the configured HTTP transport used for all REST API requests. It's optimized with connection pooling and appropriate timeouts.
var ( SystemProxy = &httputil.ReverseProxy{ Director: systemProxyDirector, Transport: RestHttpClient.Transport, } )
var UploadHttpClient = &http.Client{ Transport: RestHttpTransport, Timeout: time.Hour, }
UploadHttpClient is the HTTP client used for upload requests, which might need a longer timeout due to the actual upload.
Functions ¶
func Apply ¶
Apply makes a REST API request and unmarshals the response data into the target object. It handles authentication, error parsing, and JSON unmarshaling.
Parameters:
- ctx: Context for the request, may contain authentication tokens - path: API endpoint path - method: HTTP method (GET, POST, PUT, etc.) - param: Request parameters or body content - target: Destination object for unmarshaled response data
Returns: an error if the request fails or response cannot be unmarshaled.
func As ¶ added in v0.5.26
As makes a REST API request and returns the response data unmarshaled into the specified type T. This is a generic version of Apply that returns the target object directly.
Parameters:
- ctx: Context for the request, may contain authentication tokens - path: API endpoint path - method: HTTP method (GET, POST, PUT, etc.) - param: Request parameters or body content
Returns: the unmarshaled object of type T and any error encountered.
func ResponseAs ¶ added in v0.5.26
ResponseAs is a generic helper that unmarshals a response into type T.
Parameters:
- r: The Response object containing data to unmarshal
Returns: the unmarshaled object of type T and any error encountered
func SpotApply ¶ added in v0.5.23
func SpotApply(ctx context.Context, client SpotClient, path, method string, param any, target any) error
SpotApply makes a REST API request through a SpotClient and unmarshals the response into target. This is similar to Apply but uses a SpotClient for the request.
Parameters:
- ctx: Context for the request - client: SpotClient to use for the API request - path: API endpoint path - method: HTTP method (GET, POST, PUT, etc.) - param: Request parameters or body content - target: Destination object for unmarshaled response data
Returns: an error if the request fails or response cannot be unmarshaled.
func SpotAs ¶ added in v0.5.26
func SpotAs[T any](ctx context.Context, client SpotClient, path, method string, param any) (T, error)
SpotAs makes a REST API request through a SpotClient and returns the response data unmarshaled into type T. This is a generic version of SpotApply that returns the target object directly.
Parameters: - ctx: Context for the request - client: SpotClient to use for the API request - path: API endpoint path - method: HTTP method (GET, POST, PUT, etc.) - param: Request parameters or body content
Returns: the unmarshaled object of type T and any error encountered.
Types ¶
type ApiKey ¶ added in v0.5.32
ApiKey represents an API key with its secret for signing requests. It contains the key ID and secret key used for request signing.
func NewApiKey ¶ added in v0.5.32
NewApiKey creates a new ApiKey instance from separate key ID and secret parameters. This is the recommended way to create an ApiKey instance.
Parameters: - keyID: The API key identifier - secret: The secret key as a base64-encoded string
Returns: - An ApiKey instance and nil if successful - nil and an error if the secret cannot be properly decoded or is invalid
The secret is a base64url-encoded (using - and _ characters) Ed25519 private key provided by the server.
type ContextRequest ¶ added in v0.5.6
type ContextRequest int
const ( BackendURL ContextRequest = 1 SkipDebugLog ContextRequest = 2 UploadProgress ContextRequest = 3 )
type Error ¶ added in v0.2.2
type Error struct {
Response *Response
// contains filtered or unexported fields
}
Error represents an error returned by a REST API endpoint. It wraps the Response object and provides standard error interfaces.
type HttpError ¶ added in v0.5.15
HttpError represents an HTTP transport error that occurred during a REST API request. It captures HTTP status codes and response bodies for debugging.
type Param ¶ added in v0.2.2
Param is a convenience type for parameters passed to REST API requests.
type Response ¶ added in v0.2.2
type Response struct {
Result string `json:"result"` // "success" or "error" (or "redirect")
Data pjson.RawMessage `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Code int `json:"code,omitempty"` // for errors
Extra string `json:"extra,omitempty"`
Token string `json:"token,omitempty"`
Paging any `json:"paging,omitempty"`
Job any `json:"job,omitempty"`
Time any `json:"time,omitempty"`
Access any `json:"access,omitempty"`
Exception string `json:"exception,omitempty"`
RedirectUrl string `json:"redirect_url,omitempty"`
RedirectCode int `json:"redirect_code,omitempty"`
RequestID string `json:"-"` // X-Request-Id header from HTTP response
// contains filtered or unexported fields
}
Response represents a REST API response with standard fields. It handles different result types and provides methods to access response data.
func Do ¶
Do executes a REST API request and returns the raw Response object. It handles token authentication, token renewal, parameter encoding, and error parsing.
Parameters:
- ctx: Context for the request, may contain authentication tokens - path: API endpoint path - method: HTTP method (GET, POST, PUT, etc.) - param: Request parameters or body content
Returns: the raw Response object and any error encountered during the request.
func SpotDo ¶ added in v0.5.23
func SpotDo(ctx context.Context, client SpotClient, path, method string, param any) (*Response, error)
SpotDo executes a REST API request through a SpotClient and returns the raw Response object. This is the base function used by SpotApply and SpotAs.
Parameters:
- ctx: Context for the request - client: SpotClient to use for the API request - path: API endpoint path - method: HTTP method (GET, POST, PUT, etc.) - param: Request parameters or body content
Returns: the raw Response object and any error encountered during the request.
func SpotUpload ¶ added in v0.5.24
func SpotUpload(ctx context.Context, client SpotClient, req, method string, param Param, f io.Reader, mimeType string) (*Response, error)
SpotUpload uploads a file using a SpotClient. This is similar to Upload but uses a specific SpotClient for the request.
Parameters:
- ctx: Context for the request - client: SpotClient to use for the API request - req: API endpoint path - method: HTTP method for the initial API request - param: Parameters for the initial API request - f: Reader for the file content to upload - mimeType: MIME type of the file content
Returns: the API response after upload completion or an error.
func Upload ¶ added in v0.4.0
func Upload(ctx context.Context, req, method string, param Param, f io.Reader, mimeType string) (*Response, error)
Upload uploads a file to a REST API endpoint. It automatically selects the best upload method based on file size and server capabilities (direct PUT, multi-part, or AWS S3).
Parameters:
- ctx: Context for the request - req: API endpoint path - method: HTTP method for the initial API request - param: Parameters for the initial API request - f: Reader for the file content to upload - mimeType: MIME type of the file content
Returns: the API response after upload completion or an error.
func (*Response) Apply ¶ added in v0.4.2
Apply unmarshals the response data into the provided value.
Parameters:
- v: The target object to unmarshal into
Returns: an error if unmarshaling fails
func (*Response) ApplyContext ¶ added in v0.5.3
ApplyContext unmarshals the response data into the provided value using a context.
Parameters:
- ctx: Context for unmarshaling - v: The target object to unmarshal into
Returns: an error if unmarshaling fails
func (*Response) FullRaw ¶ added in v0.5.10
FullRaw returns the complete response as a map, including both the data payload and all metadata fields (result, error, code, etc.).
func (*Response) Get ¶ added in v0.4.4
Get retrieves a value from the response data by a slash-separated path. For example, "user/name" would access the "name" field inside the "user" object.
Parameters:
- v: Slash-separated path to the requested value
Returns: the value at the specified path and any error encountered
func (*Response) GetString ¶ added in v0.4.4
GetString retrieves a string value from the response data by a slash-separated path. This is a convenience method that calls Get() and converts the result to a string.
Parameters:
- v: Slash-separated path to the requested string value
Returns: the string value at the specified path and any error encountered
func (*Response) OffsetGet ¶ added in v0.5.11
OffsetGet implements the typutil.Getter interface for Response objects. It allows accessing response fields by key, with special handling for metadata keys prefixed with '@' (e.g., @error, @code).
func (*Response) ParseData ¶ added in v0.5.12
func (r *Response) ParseData()
ParseData parses the JSON data in the response. This is called automatically by Value() and ValueContext() methods.
func (*Response) Raw ¶ added in v0.5.7
Raw returns the parsed data from the response. It's implemented as r.Value() for compatibility with older code.
func (*Response) ReadValue ¶ added in v0.2.2
ReadValue returns the parsed data from the response. It's an alias for Value() that satisfies interfaces requiring a context parameter.
func (*Response) Value ¶ added in v0.4.4
Value returns the parsed data from the response. It lazily parses the JSON data on first access and caches the result.
Returns: the parsed data and any error encountered during parsing
func (*Response) ValueContext ¶ added in v0.5.3
ValueContext returns the parsed data from the response, similar to Value(). It's provided for interface compatibility with methods requiring a context.
Parameters:
- ctx: Context (not used internally but provided for interface compatibility)
Returns: the parsed data and any error encountered during parsing
type RouterType ¶ added in v0.1.3
type RouterType struct {
}
var Router *RouterType = &RouterType{}
func (*RouterType) ServeHTTP ¶ added in v0.1.3
func (h *RouterType) ServeHTTP(w http.ResponseWriter, req *http.Request)
type SenderInterface ¶ added in v0.5.1
var Sender SenderInterface = restSender{}
type SpotClient ¶ added in v0.5.23
type SpotClient interface {
Query(ctx context.Context, target string, body []byte) ([]byte, error)
}
SpotClient is an interface fulfilled by spotlib.Client that provides the necessary functionality for making API requests through a Spot connection. Using this interface helps avoid dependency loops between packages.
type Time ¶ added in v0.1.4
func (Time) MarshalContextJSON ¶ added in v0.5.3
func (Time) MarshalJSON ¶ added in v0.3.0
func (*Time) UnmarshalContextJSON ¶ added in v0.5.3
func (*Time) UnmarshalJSON ¶ added in v0.3.0
type Token ¶ added in v0.2.0
type Token struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
Type string `json:"token_type"`
ClientID string
Expires int `json:"expires_in"`
}
Token represents an OAuth2 token with refresh capabilities. It contains both access and refresh tokens and methods to use them in requests.
type TokenSender ¶ added in v0.5.25
type TokenSender struct {
Token string
}
type UploadInfo ¶ added in v0.4.0
type UploadInfo struct {
MaxPartSize int64 // maximum size of a single part in MB, defaults to 1024 (1GB)
ParallelUploads int // number of parallel uploads to perform (defaults to 3)
// contains filtered or unexported fields
}
UploadInfo represents configuration and state for file uploads. It supports different upload methods: direct PUT, multi-part uploads, and AWS S3 uploads for large files.
func PrepareUpload ¶ added in v0.4.0
func PrepareUpload(req map[string]any) (*UploadInfo, error)
PrepareUpload creates an UploadInfo from the server response to an upload request. It parses server-provided upload parameters and prepares for the actual upload.
Parameters:
- req: Map containing upload configuration from the server
Returns: an UploadInfo object or an error if preparation fails.
func (*UploadInfo) Do ¶ added in v0.4.0
func (u *UploadInfo) Do(ctx context.Context, f io.Reader, mimeType string, ln int64) (*Response, error)
Do performs the actual file upload using the appropriate method. It automatically chooses between direct PUT, multi-part, or AWS S3 uploads based on file size and server capabilities.
Parameters:
- ctx: Context for the upload request - f: Reader for the file content to upload - mimeType: MIME type of the file content - ln: Length of the file in bytes, or -1 if unknown
Returns: the API response after upload completion or an error.
func (*UploadInfo) String ¶ added in v0.4.0
func (u *UploadInfo) String() string
String returns the upload URL as a string representation of the UploadInfo.
type UploadProgressFunc ¶ added in v0.6.8
type UploadProgressFunc func(bytesUploaded int64)
UploadProgressFunc is a callback function for upload progress updates. It receives the number of bytes that have been successfully uploaded. The function is called after each part completes uploading.
type UploadWriteHandler ¶ added in v0.6.9
type UploadWriteHandler struct {
// contains filtered or unexported fields
}
func SpotUploadWriter ¶ added in v0.6.9
func SpotUploadWriter(ctx context.Context, client SpotClient, req, method string, param Param, mimeType string) (*UploadWriteHandler, error)
func UploadWriter ¶ added in v0.6.9
func (*UploadWriteHandler) Close ¶ added in v0.6.9
func (up *UploadWriteHandler) Close() error
func (*UploadWriteHandler) CloseWithResponse ¶ added in v0.6.9
func (up *UploadWriteHandler) CloseWithResponse() (*Response, error)