api

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 19 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 提供 Pixiv App API 的传输层、媒体 URL 策略与失败分类。

本包不承载内容语义:端点路由与响应映射由 sdk/pixiv 持有,OAuth token 交换在 子包 oauth。

包的组成:Client 发送 App 请求并缓存已校验的资源 locator,由 New 构造; Config 是构造参数,Failure 是脱敏失败,RequiredList 与 RequiredObject 解码必需字段;routes.go 与 profile.go 声明路由、参数和请求头。

Index

Constants

View Source
const (
	AppAPIBase   = "https://app-api.pixiv.net"
	OAuthBase    = "https://oauth.secure.pixiv.net"
	AppReferer   = AppAPIBase + "/"
	AppUserAgent = "PixivAndroidApp/5.0.234 (Android 11; Pixel 5)"
	AppOS        = "android"
	AppOSVersion = "11"
	AppVersion   = "5.0.234"

	OAuthClientID     = "MOBrBDS8blbauoSck0ZfDbtuzpyT"
	OAuthClientSecret = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj"
	OAuthRedirectURI  = AppAPIBase + "/web/v1/users/auth/pixiv/callback"
)

AppAPIBase 与 OAuthBase 是 Pixiv App 与 OAuth 的固定入口,其余常量是请求头基线。

View Source
const (
	PathOAuthToken           = "/auth/token"
	PathLogin                = "/web/v1/login"
	PathOAuthStart           = "/web/v1/users/auth/pixiv/start"
	PathSearchIllust         = "/v1/search/illust"
	PathIllustDetail         = "/v1/illust/detail"
	PathIllustRelated        = "/v2/illust/related"
	PathIllustSeries         = "/v1/illust/series"
	PathIllustRanking        = "/v1/illust/ranking"
	PathIllustRecommended    = "/v1/illust/recommended"
	PathIllustNew            = "/v1/illust/new"
	PathIllustFollow         = "/v2/illust/follow"
	PathIllustMyPixiv        = "/v2/illust/mypixiv"
	PathIllustComments       = "/v3/illust/comments"
	PathIllustCommentAdd     = "/v1/illust/comment/add"
	PathIllustCommentDelete  = "/v1/illust/comment/delete"
	PathIllustBookmarkDetail = "/v2/illust/bookmark/detail"
	PathBookmarkAdd          = "/v2/illust/bookmark/add"
	PathBookmarkDelete       = "/v1/illust/bookmark/delete"
	PathUserIllusts          = "/v1/user/illusts"
	PathUserBookmarksIllust  = "/v1/user/bookmarks/illust"
	PathUserBookmarkTags     = "/v1/user/bookmark-tags/illust"
	PathTrendingTagsIllust   = "/v1/trending-tags/illust"
	PathUgoiraMetadata       = "/v1/ugoira/metadata"

	PathSearchUser            = "/v1/search/user"
	PathUserDetail            = "/v1/user/detail"
	PathUserRecommended       = "/v1/user/recommended"
	PathUserRelated           = "/v1/user/related"
	PathUserFollowing         = "/v1/user/following"
	PathUserFollower          = "/v1/user/follower"
	PathUserBlocked           = "/v2/user/list"
	PathUserMyPixiv           = "/v1/user/mypixiv"
	PathUserNovels            = "/v1/user/novels"
	PathUserNovelBookmarks    = "/v1/user/bookmarks/novel"
	PathUserNovelBookmarkTags = "/v1/user/bookmark-tags/novel"
	PathNovelBookmarkDetail   = "/v2/novel/bookmark/detail"
	PathNovelBookmarkAdd      = "/v2/novel/bookmark/add"
	PathNovelBookmarkDelete   = "/v1/novel/bookmark/delete"
	PathStamps                = "/v1/stamps"
	PathFollowAdd             = "/v1/user/follow/add"
	PathFollowDelete          = "/v1/user/follow/delete"

	PathSearchNovel        = "/v1/search/novel"
	PathNovelDetail        = "/v2/novel/detail"
	PathNovelContent       = "/v1/novel/content"
	PathNovelRanking       = "/v1/novel/ranking"
	PathNovelRecommended   = "/v1/novel/recommended"
	PathNovelNew           = "/v1/novel/new"
	PathNovelFollow        = "/v1/novel/follow"
	PathNovelMyPixiv       = "/v1/novel/mypixiv"
	PathNovelSeries        = "/v2/novel/series"
	PathNovelComments      = "/v2/novel/comments"
	PathNovelCommentAdd    = "/v1/novel/comment/add"
	PathNovelCommentDelete = "/v1/novel/comment/delete"
)

PathOAuthToken 等常量是 App API 路径。

View Source
const (
	ParamIllustID         = "illust_id"
	ParamIllustSeriesID   = "illust_series_id"
	ParamUserID           = "user_id"
	ParamRestrict         = "restrict"
	ParamTag              = "tag"
	ParamTags             = "tags[]"
	ParamOffset           = "offset"
	ParamMaxBookmarkID    = "max_bookmark_id"
	ParamMaxIllustID      = "max_illust_id"
	ParamLastOrder        = "last_order"
	ParamMode             = "mode"
	ParamDate             = "date"
	ParamWord             = "word"
	ParamSearchTarget     = "search_target"
	ParamSort             = "sort"
	ParamDuration         = "duration"
	ParamStartDate        = "start_date"
	ParamEndDate          = "end_date"
	ParamSearchAIType     = "search_ai_type"
	ParamRatioPattern     = "ratio_pattern"
	ParamContentType      = "content_type"
	ParamType             = "type"
	ParamFilter           = "filter"
	ParamTool             = "tool"
	ParamBookmarkNumMin   = "bookmark_num_min"
	ParamBookmarkNumMax   = "bookmark_num_max"
	ParamWidthMin         = "width_min"
	ParamWidthMax         = "width_max"
	ParamHeightMin        = "height_min"
	ParamHeightMax        = "height_max"
	ParamComment          = "comment"
	ParamCommentID        = "comment_id"
	ParamParentCommentID  = "parent_comment_id"
	ParamStampID          = "stamp_id"
	ParamSeedIllustIDs    = "seed_illust_ids[]"
	ParamSeedUserID       = "seed_user_id"
	ParamViewed           = "viewed[]"
	ParamMinRecentIllusts = "min_bookmark_id_for_recent_illust"
	ParamMaxRecommend     = "max_bookmark_id_for_recommend"
	ParamIncludeRanking   = "include_ranking_illusts"
	ParamIncludePrivacy   = "include_privacy_policy"

	ParamNovelID              = "novel_id"
	ParamSeriesID             = "series_id"
	ParamMaxNovelID           = "max_novel_id"
	ParamAlreadyRecommended   = "already_recommended"
	ParamIncludeRankingNovels = "include_ranking_novels"
)

ParamIllustID 等常量是 App API 的 query/form 参数名。

Variables

View Source
var ErrMalformedResponse = errors.New("pixiv upstream returned a malformed response")

ErrMalformedResponse 可由 errors.Is 用来识别 malformed 失败。

Functions

func AppHeaders added in v1.3.0

func AppHeaders(accessToken string) map[string]string

AppHeaders 返回每次请求新建的 App 请求头;accessToken 非空时附带 Bearer 认证。

func NewHTTPClient added in v1.3.0

func NewHTTPClient(injected *http.Client, interval time.Duration, logger *slog.Logger) (*http.Client, bool)

NewHTTPClient 保留注入 client 的生命周期与设置。第二个返回值报告所有权:只有新建的 client 可以由 SDK 关闭。

func OAuthHeaders added in v1.3.0

func OAuthHeaders() map[string]string

OAuthHeaders 返回表单提交使用的请求头,包含 form Content-Type,不带认证。

func ValidStampURL added in v1.3.0

func ValidStampURL(rawURL string) bool

ValidStampURL 按上游 stamp 契约校验绝对 request URI:必须位于官方媒体主机,不接受 调用方额外添加的资源主机。

Types

type Client

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

Client 发送 Pixiv App 请求,持有共享 HTTP 生命周期与已校验的资源 locator 缓存。

resourceMu 保护 resourceURLs;只有本 client 创建的 HTTP 连接会被关闭。

func New

func New(cfg Config) *Client

New 按 cfg 构造 App API client;零值使用默认 HTTP client 且不带认证。

func (*Client) CacheResource added in v1.3.0

func (c *Client) CacheResource(ref, rawURL string) error

CacheResource 只登记已通过校验的 locator;ref 是公开模型持有的不透明引用。

func (*Client) CachedResource added in v1.3.0

func (c *Client) CachedResource(ref string) (string, bool)

CachedResource 返回本运行时为 ref 登记的 locator。

func (*Client) CloseIdleConnections added in v1.3.0

func (c *Client) CloseIdleConnections()

CloseIdleConnections 只释放本运行时创建的 client 连接。

func (*Client) GetJSON added in v1.3.0

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

GetJSON 提供给 endpoint family 的窄 transport 能力。route、query、wire DTO 与响应校验由具体 endpoint package 拥有;这里仅负责 App API 的请求、 静态认证与既有 Retry-After 读取契约。

func (*Client) GetRaw added in v1.3.0

func (c *Client) GetRaw(ctx context.Context, path string, query url.Values) ([]byte, error)

GetRaw 提供给需要保留原始响应体的 endpoint family。App API adapter 仍只负责 认证头、状态码处理与既有重试契约,正文语义由调用方 family 解释。

func (*Client) OpenResource added in v1.3.0

func (c *Client) OpenResource(ctx context.Context, request OpenRequest) (*Response, error)

OpenResource 以不带产品凭据的 client 流式读取允许列表内的 URL;注入的 redirect 回调改写目标后,最终 URL 仍会再次校验。

func (*Client) PostForm added in v1.3.0

func (c *Client) PostForm(ctx context.Context, path string, form url.Values) error

PostForm 提供给 mutation endpoint family 的窄 form transport,不重放写入。 认证头与状态码由此层处理;具体 route 和字段由 family 持有。

func (*Client) PostFormJSON added in v1.3.0

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

PostFormJSON 提供给需要读取 mutation 响应的 endpoint family。成功响应必须 包含可解码 JSON;不重放请求,避免把不确定的 mutation 当作安全失败处理。

func (*Client) ValidateResourceURL added in v1.3.0

func (c *Client) ValidateResourceURL(rawURL string) error

ValidateResourceURL 按 Pixiv 媒体的 scheme、主机与路径策略校验 rawURL。

type Config added in v1.3.0

type Config struct {
	HTTPClient *http.Client
	// OwnHTTPClient 表示 HTTPClient 由 NewHTTPClient 创建,关闭时只释放这种 client。
	OwnHTTPClient  bool
	ResourceHosts  []string
	AccessToken    string
	AcceptLanguage string
	UserID         int64
	// Logger 记录请求结果与重试决策;nil 时不输出。
	Logger *slog.Logger
}

Config 提供 App API 客户端的构造参数;零值使用默认 HTTP client 和无认证。

type Failure added in v1.3.0

type Failure struct {
	Kind          FailureKind
	TransportKind TransportKind
	StatusCode    int
	RetryAfter    time.Duration
	HasRetryAfter bool
	// contains filtered or unexported fields
}

Failure 表示 adapter 向 facade 交付的脱敏失败。它绝不保存响应 body、URL、 header、token、cookie 或 Web envelope message;只有取消和 deadline 可作为 可 unwrap 的底层原因,以保留 Go 的 context 语义。

func HTTPStatus added in v1.3.0

func HTTPStatus(status int) Failure

HTTPStatus 构造不带 Retry-After 的非 2xx 失败。

func HTTPStatusWithRetryAfter added in v1.3.0

func HTTPStatusWithRetryAfter(status int, retryAfter time.Duration, present bool) Failure

HTTPStatusWithRetryAfter 构造带可选 Retry-After 的非 2xx 失败;present 为 false 时 RetryAfter 无意义。

func MalformedResponse added in v1.3.0

func MalformedResponse() Failure

MalformedResponse 构造响应无法解码的失败。

func Transport added in v1.3.0

func Transport(err error) Failure

Transport 把传输错误转成脱敏失败;取消与 deadline 保留为可 unwrap 的原因。

func (Failure) Error added in v1.3.0

func (e Failure) Error() string

Error 按 FailureKind 输出固定的英文文本,不含 URL、header、body 或上游消息。

func (Failure) Is added in v1.3.0

func (e Failure) Is(target error) bool

Is 支持用 ErrMalformedResponse 判断 malformed 失败。

func (Failure) Unwrap added in v1.3.0

func (e Failure) Unwrap() error

Unwrap 返回保留的 context 取消或 deadline 原因。

type FailureKind added in v1.3.0

type FailureKind string

FailureKind 枚举 Failure 的稳定分类。

const (
	FailureHTTPStatus        FailureKind = "http_status"
	FailureMalformed         FailureKind = "malformed_response"
	FailureResourceForbidden FailureKind = "resource_forbidden"
	FailureTransport         FailureKind = "transport"
)

FailureHTTPStatus 表示上游返回非 2xx;FailureMalformed 表示响应无法解码; FailureResourceForbidden 表示资源 locator 未通过策略;FailureTransport 表示传输失败。

type OpenRequest added in v1.3.0

type OpenRequest struct {
	URL    string
	Method string
	Header http.Header
}

OpenRequest 描述一次资源读取;Method 为空时按 GET 发送,Header 由调用方校验后传入。

type RequiredList added in v1.3.0

type RequiredList[T any] struct {
	Items   []T
	Present bool
	Valid   bool
}

RequiredList 解码一个必需数组字段,并保留其存在性与有效性。

func (*RequiredList[T]) UnmarshalJSON added in v1.3.0

func (l *RequiredList[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON 先把字段标记为已出现;数组解码失败时返回错误,Present 保持 true 供 端点报告上下文。

type RequiredObject added in v1.3.0

type RequiredObject[T any] struct {
	Value   T
	Present bool
	Valid   bool
}

RequiredObject 解码一个必需对象字段,并保留其存在性与有效性。

func (*RequiredObject[T]) UnmarshalJSON added in v1.3.0

func (o *RequiredObject[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON 先把字段标记为已出现;对象解码失败时返回错误,Present 保持 true 供 端点报告上下文。

type Response added in v1.3.0

type Response struct {
	StatusCode int
	Header     http.Header
	Body       io.ReadCloser
}

Response 保留响应流所有权,调用方负责关闭 Body。

type TransportKind added in v1.3.0

type TransportKind string

TransportKind 标记传输失败的安全子类,供 facade 决定错误映射。

const (
	TransportDNS               TransportKind = "dns"
	TransportTLS               TransportKind = "tls"
	TransportProxy             TransportKind = "proxy"
	TransportConnectionRefused TransportKind = "connection_refused"
	TransportConnectionReset   TransportKind = "connection_reset"
	TransportTimeout           TransportKind = "timeout"
	TransportUnknown           TransportKind = "unknown"
)

TransportDNS 等值是 TransportKind 的全部取值,分类只依赖标准库的 typed cause。

Directories

Path Synopsis
Package oauth 管理 Pixiv 身份状态与 OAuth token 交换,不承载内容 API。
Package oauth 管理 Pixiv 身份状态与 OAuth token 交换,不承载内容 API。

Jump to

Keyboard shortcuts

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