client

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package client implements the shared HTTP, session, signing, response, and request-policy module used by every bpi-go domain. Most applications should construct the root bpi.Client; direct use is intended for composing a single domain module or building advanced custom requests.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingData means the remote interface returned success without a
	// required payload.
	ErrMissingData = errors.New("bpi: response is missing required data")

	// ErrAuthenticationRequired means an operation needs an authenticated
	// account or CSRF token.
	ErrAuthenticationRequired = errors.New("bpi: authentication required")
)

Functions

func IsPermissionError

func IsPermissionError(err error) bool

IsPermissionError reports whether err represents an authorization failure.

func IsRiskControl

func IsRiskControl(err error) bool

IsRiskControl reports whether err represents Bilibili risk control.

func NewFormRequest

func NewFormRequest(ctx context.Context, endpoint string, query, form url.Values) (*http.Request, error)

NewFormRequest builds a form-encoded POST request.

func NewJSONRequest

func NewJSONRequest(ctx context.Context, endpoint string, query url.Values, value any) (*http.Request, error)

NewJSONRequest builds a JSON-encoded POST request.

func NewQueryRequest

func NewQueryRequest(ctx context.Context, method, endpoint string, query url.Values) (*http.Request, error)

NewQueryRequest builds a context-bound request and merges query values with any query already present in endpoint.

func RequiresLogin

func RequiresLogin(err error) bool

RequiresLogin reports whether err represents an unauthenticated response.

func RequiresVIP

func RequiresVIP(err error) bool

RequiresVIP reports whether err represents a VIP-only response.

func SendOptionalPayload

func SendOptionalPayload[T any](ctx context.Context, client *Client, request *http.Request, operation string) (*T, error)

SendOptionalPayload executes request and returns an optional Bilibili business payload.

func SendPayload

func SendPayload[T any](ctx context.Context, client *Client, request *http.Request, operation string) (T, error)

SendPayload executes request and returns a required Bilibili business payload. It is the generic custom-request counterpart to domain methods.

Types

type APIError

type APIError struct {
	Code    int
	Message string
}

APIError reports a non-zero Bilibili response code.

func (*APIError) Error

func (e *APIError) Error() string

type Account

type Account struct {
	DedeUserID string
	SESSDATA   string
	BiliJCT    string
	Buvid3     string
}

Account contains the four common Cookie values used for a complete Bilibili account projection. Raw Cookie headers may contain fewer or additional pairs. Account's formatted, logged, and JSON representations are redacted.

func (Account) CSRF

func (a Account) CSRF() (string, error)

CSRF returns the account CSRF token.

func (Account) LogValue

func (a Account) LogValue() slog.Value

LogValue deliberately excludes all credential values.

func (Account) MarshalJSON

func (a Account) MarshalJSON() ([]byte, error)

MarshalJSON deliberately excludes all credential values.

func (Account) String

func (a Account) String() string

String deliberately excludes all credential values.

func (Account) Validate

func (a Account) Validate() error

Validate reports whether every field in the complete account projection is present.

type Client

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

Client is an isolated, concurrency-safe Bilibili client.

func NewClient

func NewClient(options ...Option) (*Client, error)

NewClient constructs a client without reading files, mutating global state, or performing network I/O.

func (*Client) Account

func (c *Client) Account() (Account, bool)

Account returns a copy of the current complete account, when available.

func (*Client) CSRF

func (c *Client) CSRF() (string, error)

CSRF returns the current bili_jct Cookie value. It does not require the session to contain every field needed for a complete Account projection.

func (*Client) ClearAccount

func (c *Client) ClearAccount()

ClearAccount removes all client session values.

func (*Client) Do

func (c *Client) Do(ctx context.Context, request *http.Request, operation string) (*Response, error)

Do executes request with the client's headers, session, logging, response limit, and HTTP error handling. The caller retains ownership of request; Client executes a clone.

func (*Client) HasLoginCookies

func (c *Client) HasLoginCookies() bool

HasLoginCookies reports whether the client has a non-empty SESSDATA Cookie.

func (*Client) Now

func (c *Client) Now() time.Time

Now returns the client's configured clock value. Domain modules use it for request signatures whose timestamp must share the client's testable clock.

func (*Client) Origin

func (c *Client) Origin() string

Origin returns the default Origin header used for Bilibili requests.

func (*Client) Referer

func (c *Client) Referer() string

Referer returns the default Referer header used for Bilibili requests.

func (*Client) SetAccount

func (c *Client) SetAccount(account Account) error

SetAccount atomically replaces the client's authenticated session.

func (*Client) SetCookie

func (c *Client) SetCookie(cookieHeader string) error

SetCookie atomically replaces the client's session from a raw HTTP Cookie request-header value. All valid Cookie pairs are preserved.

func (*Client) WBIValues

func (c *Client) WBIValues(ctx context.Context, values url.Values) (url.Values, error)

WBIValues returns a signed copy of values using the client's cached WBI keys and clock. The input values are never mutated.

type Envelope

type Envelope[T any] struct {
	Code    int
	Data    *T
	Message string
	Status  bool
}

Envelope is the common Bilibili JSON response wrapper. Domain methods normally return its payload directly.

func DecodeEnvelope

func DecodeEnvelope[T any](body []byte) (Envelope[T], error)

DecodeEnvelope decodes a response and preserves a private copy of body when the model does not match.

func (Envelope[T]) EnsureSuccess

func (e Envelope[T]) EnsureSuccess() error

EnsureSuccess converts a non-zero response code into APIError.

func (Envelope[T]) IntoData

func (e Envelope[T]) IntoData() (T, error)

IntoData returns a required payload without checking the response code. It is reserved for interfaces such as anonymous navigation and QR polling that carry useful state alongside a non-zero business code.

func (Envelope[T]) IntoOptionalPayload

func (e Envelope[T]) IntoOptionalPayload() (*T, error)

IntoOptionalPayload returns an optional successful payload.

func (Envelope[T]) IntoPayload

func (e Envelope[T]) IntoPayload() (T, error)

IntoPayload returns a required successful payload.

func (*Envelope[T]) UnmarshalJSON

func (e *Envelope[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON supports the response aliases observed in promoted contracts.

type HTTPError

type HTTPError struct {
	StatusCode int
}

HTTPError reports a non-successful HTTP status.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a Client before it is constructed.

func WithAccount

func WithAccount(account Account) Option

WithAccount initializes the client from a complete structured account.

func WithClock

func WithClock(now func() time.Time) Option

WithClock injects the clock used by time-dependent request signatures. Most callers should use the default system clock; this option exists for deterministic adapters and tests.

func WithCookie

func WithCookie(cookieHeader string) Option

WithCookie initializes the client from a raw HTTP Cookie request-header value. All valid Cookie pairs are preserved, including pairs unknown to bpi.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient uses a shallow copy of client for transport, redirects, and timeout policy. Cookie state is always managed independently by bpi.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger enables sanitized structured request logging. A nil logger is rejected; clients are quiet by default.

func WithMaxResponseBody

func WithMaxResponseBody(limit int64) Option

WithMaxResponseBody sets the maximum response body buffered in memory.

func WithOrigin

func WithOrigin(origin string) Option

WithOrigin changes the default Origin header for Bilibili requests.

func WithReferer

func WithReferer(referer string) Option

WithReferer changes the default Referer header for Bilibili requests.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the total HTTP request timeout.

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent changes the default User-Agent header.

type ParameterError

type ParameterError = bpierr.ParameterError

ParameterError describes an invalid caller-supplied value.

type Response

type Response struct {
	StatusCode int
	Body       []byte
	// Cookies contains a detached copy of Set-Cookie values returned by the
	// endpoint. Client has already incorporated trusted Bilibili cookies into
	// its isolated session before returning this response.
	Cookies  []http.Cookie
	Duration time.Duration
}

Response contains a fully buffered successful HTTP response. Body is an explicit raw-data surface and may contain sensitive information.

type ResponseDecodeError

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

ResponseDecodeError reports a response-model mismatch and retains a private copy of the original response for explicit recovery. Formatting and JSON serialization never include that body.

func NewResponseDecodeError

func NewResponseDecodeError(err error, body []byte) *ResponseDecodeError

NewResponseDecodeError records a response-model mismatch while keeping the body out of ordinary error formatting and logs.

func (*ResponseDecodeError) Body

func (e *ResponseDecodeError) Body() []byte

Body returns a copy of the original response body. It may contain sensitive data and should not be logged.

func (*ResponseDecodeError) Error

func (e *ResponseDecodeError) Error() string

func (*ResponseDecodeError) Unwrap

func (e *ResponseDecodeError) Unwrap() error

type ResponseTooLargeError

type ResponseTooLargeError struct {
	Limit int64
}

ResponseTooLargeError reports that a response exceeded the configured in-memory body limit.

func (*ResponseTooLargeError) Error

func (e *ResponseTooLargeError) Error() string

type TransportError

type TransportError struct {
	Operation string
	Err       error
}

TransportError wraps an error returned while performing an HTTP request.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Jump to

Keyboard shortcuts

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