api

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package api is the JumpServer REST transport.

It owns the shared *http.Client (cookie jar included), JSON parsing, error classification, the retry policy and limit/offset pagination. Login orchestration lives in internal/auth; this package only moves bytes.

Error classification mirrors the Python reference implementation: HTTP 401 raises AuthError (bad or expired token), any other non-2xx raises APIError, and a transport failure raises APIError with StatusCode == 0.

Dependency direction: api depends on nothing else in this module.

Index

Constants

View Source
const DefaultPageSize = 100

DefaultPageSize is the page size used by GetAll.

View Source
const DefaultTimeout = 15 * time.Second

DefaultTimeout is the per-request HTTP timeout (DESIGN.md「数值基线」).

Variables

This section is empty.

Functions

func IsTransportFailure

func IsTransportFailure(err error) bool

IsTransportFailure reports whether err is an APIError with StatusCode == 0, i.e. no response was received.

func NormalizeBaseURL added in v0.1.5

func NormalizeBaseURL(raw string) string

NormalizeBaseURL trims whitespace, strips trailing slashes and adds https:// when the scheme is missing.

It is exported so callers that hold an address from somewhere else — a server configuration entry, a candidate chosen by the failover policy, or the address a cached session is bound to — can compare addresses the way the HTTP client does. Two spellings of one address must not look like two endpoints (DESIGN.md「端点故障转移」第 1 点).

func WithRetryBudget

func WithRetryBudget(ctx context.Context, max int) context.Context

WithRetryBudget returns a context that caps how many times requests made through it are retried.

It exists for callers that are probing rather than working: deciding whether an endpoint is usable should not pay the full retry schedule on a server that answers 502 after a five-second stall — four attempts turned one probe into twenty-four seconds of dead time.

A budget of 0 means a single attempt. A negative budget or an absent value means the client default.

Types

type APIError

type APIError struct {
	StatusCode int
	Body       string
}

APIError reports any other API failure.

StatusCode is the HTTP status of the failed response, or 0 when the request never produced a response (transport failure, timeout, cancellation).

func AsAPIError

func AsAPIError(err error) (*APIError, bool)

AsAPIError extracts an *APIError from err, unwrapping as needed.

func (*APIError) Error

func (e *APIError) Error() string

type AuthError

type AuthError struct {
	StatusCode int
	Body       string
}

AuthError reports a rejected or expired credential (HTTP 401).

The endpoint-selection policy treats AuthError as terminal: switching to another address cannot fix a credential problem (DESIGN.md「端点故障转移」).

Body is a truncated copy of the response body and never contains request headers, so a bearer token cannot leak through an error.

func AsAuthError

func AsAuthError(err error) (*AuthError, bool)

AsAuthError extracts an *AuthError from err, unwrapping as needed.

func (*AuthError) Error

func (e *AuthError) Error() string

type Client

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

Client is an HTTP client bound to one JumpServer base URL.

It is safe for concurrent use once login has finished: the embedded *http.Client and its cookie jar are, and the token fields are only written while the session is still private to the login flow.

func New

func New(baseURL string) *Client

New returns a Client for baseURL that connects directly.

The URL is normalized: whitespace trimmed, trailing slashes removed and https:// assumed when the scheme is missing. The client gets a cookie jar because the Django form login only communicates through cookies.

The transport is set EXPLICITLY, with Proxy == nil, so the client does not inherit http.DefaultTransport and therefore never reads HTTP_PROXY/HTTPS_PROXY (DESIGN.md「代理策略」). Leaving the field unset used to make the REST calls honour the environment while every other transport (probe, SSH, SFTP, WebSocket) connected directly — probe and login then measured different networks.

func NewWithProxy

func NewWithProxy(baseURL string, px netproxy.Proxy) *Client

NewWithProxy returns a Client for baseURL that honours the proxy policy. A direct policy (the zero value) connects directly.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the normalized base URL.

func (*Client) Bearer

func (c *Client) Bearer() string

Bearer returns the current bearer token.

func (*Client) CSRF

func (c *Client) CSRF() string

CSRF returns the current CSRF token.

func (*Client) Cookie

func (c *Client) Cookie(name string) string

Cookie returns the value of the named cookie in the client's jar for the base URL, or "" when absent.

func (*Client) Delete added in v0.2.0

func (c *Client) Delete(ctx context.Context, path string, out any) error

Delete performs an authenticated DELETE and decodes the JSON response into out. out may be nil.

Delete carries no body: the api.do signature always marshals a body argument, and an empty JSON object would be rejected by views that expect no payload, so the body is left nil here.

JumpServer's asset detail view answers DELETE on the resource itself (e.g. /api/v1/assets/hosts/<id>/); it rejects POST with "method_not_allowed", so a delete cannot be expressed as a POST with an ?action=delete query — that form is only valid on the list view.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, params url.Values, out any) error

Get performs an authenticated GET and decodes the JSON body into out. out may be nil when the body is not needed.

func (*Client) GetAll

func (c *Client) GetAll(ctx context.Context, path string, params url.Values) ([]json.RawMessage, error)

GetAll walks every page of a limit/offset paginated list endpoint and returns the raw items.

JumpServer answers {"count": N, "results": [...]}; a bare JSON array (pagination disabled server-side) is returned as-is. Iteration stops on an empty page, when the accumulated offset reaches count, or after maxPages pages — the last bound keeps a server that ignores offset from looping the client forever.

func (*Client) HTTP

func (c *Client) HTTP() *http.Client

HTTP exposes the underlying client (used by internal/auth for the form login and by tests to swap transports).

func (*Client) Patch added in v0.2.0

func (c *Client) Patch(ctx context.Context, path string, body, out any) error

Patch performs an authenticated PATCH with a JSON body and decodes the JSON response into out. out may be nil.

PATCH changes only the fields the body carries, which is what the asset view advertises alongside PUT (Allow: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS).

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body, out any) error

Post performs an authenticated POST with a JSON body and decodes the JSON response into out. out may be nil.

func (*Client) Put added in v0.2.0

func (c *Client) Put(ctx context.Context, path string, body, out any) error

Put performs an authenticated PUT with a JSON body and decodes the JSON response into out. out may be nil.

JumpServer uses PUT for a full update of an existing object (asset field changes, account edits); PATCH is not exposed by the asset views.

func (*Client) SetBearer

func (c *Client) SetBearer(token string)

SetBearer stores the API bearer token sent as "Authorization: Bearer".

func (*Client) SetCSRF

func (c *Client) SetCSRF(token string)

SetCSRF stores the CSRF token sent as "X-CSRFToken".

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(hc *http.Client)

SetHTTPClient replaces the underlying HTTP client. Intended for tests and for wiring a client with custom TLS settings.

Jump to

Keyboard shortcuts

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