client

package
v1.0.44 Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HandleResponse

func HandleResponse(resp *larkcore.ApiResp, opts ResponseOptions) error

HandleResponse routes a raw *larkcore.ApiResp to the appropriate output:

  1. If Content-Type is JSON, check for business errors first (even with --output).
  2. If --output is set and response is not a JSON error, save to file.
  3. If Content-Type is non-JSON and no --output, auto-save binary to file.

func IsJSONContentType

func IsJSONContentType(ct string) bool

IsJSONContentType reports whether the Content-Type header indicates a JSON response.

func PaginateWithJq added in v1.0.3

func PaginateWithJq(ctx context.Context, ac *APIClient, request RawApiRequest,
	jqExpr string, out io.Writer, pagOpts PaginationOptions,
	checkErr func(interface{}, core.Identity) error) error

PaginateWithJq aggregates all pages, checks for API errors, then applies a jq filter. If checkErr detects an error, the raw result is printed as JSON before returning the error.

func ParseJSONResponse

func ParseJSONResponse(resp *larkcore.ApiResp) (interface{}, error)

ParseJSONResponse decodes a raw SDK response body as JSON. CallAPI and HandleResponse both delegate to this function.

func ResolveFilename

func ResolveFilename(resp *larkcore.ApiResp) string

ResolveFilename picks a filename from the response headers. Priority: Content-Disposition filename > Content-Type extension > "download.bin".

func SaveResponse

func SaveResponse(fio fileio.FileIO, resp *larkcore.ApiResp, outputPath string) (map[string]interface{}, error)

SaveResponse writes an API response body to the given outputPath and returns metadata. It delegates to FileIO.Save for path validation and atomic write; fio must not be nil.

func WrapDoAPIError deprecated added in v1.0.6

func WrapDoAPIError(err error) error

WrapDoAPIError upgrades malformed JSON decode errors from the SDK into actionable API errors for raw `lark-cli api` calls. All other failures remain network errors.

Already-classified errors pass through unchanged: any *output.ExitError (legacy envelope from output.ErrAuth / output.ErrAPI / output.ErrWithHint) and any typed *errs.* error (carries an embedded Problem) keeps its own category and exit code. This is what makes the wrap idempotent on the auth/credential chain — resolveAccessToken returns output.ErrAuth for missing tokens, and that classification must survive the SDK boundary.

Deprecated: legacy *output.ExitError wire shape (api_error + rawAPIJSONHint on JSON-decode, network otherwise) for the wrap-from-untyped branch. Preserved so SDK Do() callers keep the original envelope until per-domain migration to typed errors. New code should route through APIClient.CheckResponse (typed *errs.APIError) or construct *errs.NetworkError / *errs.InternalError directly.

func WrapJSONResponseParseError deprecated added in v1.0.6

func WrapJSONResponseParseError(err error, body []byte) error

WrapJSONResponseParseError upgrades empty or malformed JSON response bodies into API errors with hints instead of generic parse failures.

Deprecated: legacy *output.ExitError wire shape (api_error + ExitAPI + rawAPIJSONHint). The 3-branch behaviour is preserved so existing callers of internal/client/response.go keep emitting the same envelope until per-domain migration to typed errors.

Types

type APIClient

type APIClient struct {
	Config     *core.CliConfig
	SDK        *lark.Client // All Lark API calls go through SDK
	HTTP       *http.Client // Only for non-Lark API (OAuth, MCP, etc.)
	ErrOut     io.Writer    // debug/progress output
	Credential *credential.CredentialProvider
}

APIClient wraps lark.Client for all Lark Open API calls.

func (*APIClient) CallAPI

func (c *APIClient) CallAPI(ctx context.Context, request RawApiRequest) (interface{}, error)

CallAPI is a convenience wrapper: DoAPI + ParseJSONResponse. Use DoAPI directly when the response may not be JSON (e.g. file downloads).

JSON parse failures are wrapped via WrapJSONResponseParseError so callers (notably the pagination loop and --page-all paths in cmd/api / cmd/service) see an *output.ExitError envelope (api_error for malformed JSON, network for everything else) instead of a bare fmt.Errorf. Without this, an empty or malformed page body would surface to the root handler as a plain-text "Error: ..." line, bypassing the JSON stderr envelope contract. Stage-4 framework-boundary migration will flip this wrapper to typed *errs.InternalError / *errs.NetworkError.

func (*APIClient) CheckResponse deprecated added in v1.0.41

func (c *APIClient) CheckResponse(result interface{}, identity core.Identity) error

CheckResponse inspects a Lark API response for business-level errors (non-zero code).

Deprecated: legacy *output.ExitError wire shape via output.ErrAPI / ClassifyLarkError (type "api_error" / "permission" / etc). Preserved so existing callers keep emitting the same envelope until per-domain migration to typed errors. The identity parameter is reserved for the stage-2 typed path; stage-1 ignores it.

func (*APIClient) DoAPI

func (c *APIClient) DoAPI(ctx context.Context, request RawApiRequest) (*larkcore.ApiResp, error)

DoAPI executes a raw Lark SDK request and returns the raw *larkcore.ApiResp. Unlike CallAPI which always JSON-decodes, DoAPI returns the raw response — suitable for file downloads (pass larkcore.WithFileDownload() via request.ExtraOpts) and any endpoint whose Content-Type may not be JSON.

func (*APIClient) DoSDKRequest

func (c *APIClient) DoSDKRequest(ctx context.Context, req *larkcore.ApiReq, as core.Identity, extraOpts ...larkcore.RequestOptionFunc) (*larkcore.ApiResp, error)

DoSDKRequest resolves auth for the given identity and executes a pre-built SDK request. This is the shared auth+execute path used by both DoAPI (generic API calls via RawApiRequest) and shortcut RuntimeContext.DoAPI (direct larkcore.ApiReq calls).

SDK Do() failures are normalised through WrapDoAPIError so every caller (cmd/api, RuntimeContext, shortcuts) gets the same wire shape without each one remembering to wrap. In stage 1 that wire shape is still the legacy *output.ExitError envelope (network / api_error) — the stage-4 framework boundary migration flips WrapDoAPIError to typed *errs.NetworkError / *errs.InternalError per the contract in errs/ERROR_CONTRACT.md. Errors that arrive already-classified (legacy *output.ExitError from resolveAccessToken's missing-credential paths, or a typed *errs.* from future stages) flow through unchanged.

func (*APIClient) DoStream added in v1.0.5

func (c *APIClient) DoStream(ctx context.Context, req *larkcore.ApiReq, as core.Identity, opts ...Option) (*http.Response, error)

DoStream executes a streaming HTTP request against the Lark OpenAPI endpoint. Unlike DoSDKRequest (which buffers the full body via the SDK), DoStream returns a live *http.Response whose Body is an io.Reader for streaming consumption. Auth is resolved via Credential (same as DoSDKRequest). Security headers and any extra headers from opts are applied automatically. HTTP errors (status >= 400) are handled internally: the body is read (up to 4 KB), closed, and returned as an output.ErrNetwork — callers only receive successful responses.

func (*APIClient) PaginateAll

func (c *APIClient) PaginateAll(ctx context.Context, request RawApiRequest, opts PaginationOptions) (interface{}, error)

PaginateAll fetches all pages and returns a single merged result. Use this for formats that need the complete dataset (e.g. JSON).

func (*APIClient) StreamPages

func (c *APIClient) StreamPages(ctx context.Context, request RawApiRequest, onItems func([]interface{}), opts PaginationOptions) (result interface{}, hasItems bool, err error)

StreamPages fetches all pages and streams each page's list items via onItems. Returns the last page result (for error checking), whether any list items were found, and any network error. Use this for streaming formats (ndjson, table, csv).

type Option added in v1.0.5

type Option func(*requestConfig)

Option configures API request behavior for DoStream (and future DoSDKRequest).

func WithHeaders added in v1.0.5

func WithHeaders(h http.Header) Option

WithHeaders adds extra HTTP headers to the request.

func WithTimeout added in v1.0.5

func WithTimeout(d time.Duration) Option

WithTimeout sets a request-level timeout that overrides the client default.

type PaginationOptions

type PaginationOptions struct {
	PageLimit int           // max pages to fetch; 0 = unlimited (default: 10)
	PageDelay int           // ms, default 200
	Identity  core.Identity // identity passed to checkErr; defaults to AsUser when empty
}

PaginationOptions contains pagination control options.

type RawApiRequest

type RawApiRequest struct {
	Method    string
	URL       string
	Params    map[string]interface{}
	Data      interface{}
	As        core.Identity
	ExtraOpts []larkcore.RequestOptionFunc // additional SDK request options (e.g. security headers)
}

RawApiRequest describes a raw API request.

type ResponseOptions

type ResponseOptions struct {
	OutputPath  string        // --output flag; "" = auto-detect
	Format      output.Format // output format for JSON responses
	JqExpr      string        // if set, apply jq filter instead of Format
	Out         io.Writer     // stdout
	ErrOut      io.Writer     // stderr
	FileIO      fileio.FileIO // file transfer abstraction; required when saving files (--output or binary response)
	CommandPath string        // raw cobra CommandPath() for content safety scanning
	// Identity is forwarded to CheckError (default or caller-supplied) so the
	// classifier can populate identity-aware fields (e.g. PermissionError.Identity).
	// Defaults to core.AsUser when empty.
	Identity core.Identity
	// CheckError is called on parsed JSON results. Nil defaults to (*APIClient).CheckResponse
	// with the Identity field (or AsUser when unset).
	CheckError func(result interface{}, identity core.Identity) error
}

ResponseOptions configures how HandleResponse routes a raw API response.

Jump to

Keyboard shortcuts

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