pkgsite

package module
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: BSD-3-Clause Imports: 11 Imported by: 0

README

pkgsite-go

Go Reference

Client API implementation of the pkg.go.dev v1 API.

LLM generation declaration

The basic code is modified from pkgsite's cli implementation.

License

BSD-3-Clause

Documentation

Overview

Package pkgsite provides a client for the pkg.go.dev v1 API.

Index

Constants

View Source
const (
	// DefaultServer is the default pkgsite API server.
	DefaultServer    = "https://pkg.go.dev"
	DefaultUserAgent = "pkgsite-go"
)

Variables

This section is empty.

Functions

func HTTPErrorCode

func HTTPErrorCode(err error) (code int, ok bool)

HTTPErrorCode extracts the HTTP status code from an error. It returns the code and true if the error is an APIError or HTTPError, otherwise returns 0 and false.

Types

type Candidate

type Candidate struct {
	ModulePath  string `json:"modulePath"`
	PackagePath string `json:"packagePath"`
}

Candidate is a module/package candidate returned for ambiguous package paths.

type Client

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

Client fetches data from the pkg.go.dev v1 API.

func NewClient

func NewClient(options ...Option) *Client

NewClient returns a client configured with opts.

func (*Client) FetchModule

func (c *Client) FetchModule(ctx context.Context, path string) error

FetchModule requests that pkg.go.dev fetch and index path, triggering the same action as the "Request" button shown for an unknown path on the site. path may optionally end in "@version" (e.g. "example.com/mod@v1.0.0") to request a specific version; otherwise the latest version is fetched.

Unlike the rest of Client's methods, FetchModule does not use the v1 API: it posts to the /fetch/ endpoint, which is not version-prefixed. The call blocks until pkg.go.dev confirms path has been indexed, or returns an error if the fetch failed or the request timed out.

func (*Client) ImportedBy

func (c *Client) ImportedBy(ctx context.Context, path string, opts *PackageOptions) (*PackageImportedBy, error)

ImportedBy fetches packages that import path.

func (*Client) ImportedByIter

func (c *Client) ImportedByIter(ctx context.Context, path string, options *PackageOptions) iter.Seq2[[]string, error]

ImportedByIter returns an iterator for paginating through imported-by packages. The iterator yields pages of package paths. If Next returns an error, the next call to Next will retry the same page.

func (*Client) Module

func (c *Client) Module(ctx context.Context, path string, opts *ModuleOptions) (*Module, error)

Module fetches module metadata.

func (*Client) Package

func (c *Client) Package(ctx context.Context, packagePath string, packageOptions *PackageOptions) (*Package, error)

Package fetches package metadata for packagePath.

packageOptions may specify a module path and version to disambiguate or pin the package lookup. If Doc is set, the response includes rendered package documentation in the requested format: "text", "md", "markdown", or "html". Examples may be requested only when Doc is also set. Imports and Licenses request the corresponding additional response fields.

Package validates option combinations before sending the request. Invalid local options return a regular error. Errors returned by the pkg.go.dev API are returned as *Error when the response body contains the API error format, or as HTTPError when only the HTTP status is available.

func (*Client) Packages

func (c *Client) Packages(ctx context.Context, modulePath string, opts *ModuleOptions) (*PackagesResponse, error)

Packages fetches packages in a module.

func (*Client) PackagesIter

func (c *Client) PackagesIter(ctx context.Context, modulePath string, options *ModuleOptions) iter.Seq2[[]PackageInfo, error]

PackagesIter returns an iterator for paginating through packages in a module. The iterator yields pages of packages. If Next returns an error, the next call to Next will retry the same page.

func (*Client) Search

func (c *Client) Search(ctx context.Context, query string, opts *SearchOptions) (*PaginatedResponse[SearchResult], error)

Search searches packages.

func (*Client) SearchIter

func (c *Client) SearchIter(ctx context.Context, query string, options *SearchOptions) iter.Seq2[[]SearchResult, error]

SearchIter returns an iterator for paginating through search results. The iterator yields pages of search results. If Next returns an error, the next call to Next will retry the same page.

func (*Client) Symbols

func (c *Client) Symbols(ctx context.Context, path string, opts *PackageOptions) (*PackageSymbols, error)

Symbols fetches exported symbols for a package.

func (*Client) SymbolsIter

func (c *Client) SymbolsIter(ctx context.Context, path string, options *PackageOptions) iter.Seq2[[]Symbol, error]

SymbolsIter returns an iterator for paginating through symbols. The iterator yields pages of symbols. If Next returns an error, the next call to Next will retry the same page.

func (*Client) Versions

func (c *Client) Versions(ctx context.Context, path string, opts *ModuleOptions) (*PaginatedResponse[ModuleVersion], error)

Versions fetches module versions.

By default, only tagged versions (release and prerelease) are returned. Set ModuleOptions.PseudoVersions to true to include pseudo-versions.

Note: PaginatedResponse.Total may be -1 when results span multiple pages, indicating the total count is unknown.

func (*Client) VersionsIter

func (c *Client) VersionsIter(ctx context.Context, path string, options *ModuleOptions) iter.Seq2[[]ModuleVersion, error]

VersionsIter returns an iterator for paginating through module versions. The iterator yields pages of versions. If Next returns an error, the next call to Next will retry the same page.

func (*Client) Vulnerabilities

func (c *Client) Vulnerabilities(ctx context.Context, path string, opts *ModuleOptions) (*PaginatedResponse[Vulnerability], error)

Vulnerabilities fetches module vulnerabilities.

func (*Client) VulnerabilitiesIter

func (c *Client) VulnerabilitiesIter(ctx context.Context, path string, options *ModuleOptions) iter.Seq2[[]Vulnerability, error]

VulnerabilitiesIter returns an iterator for paginating through vulnerabilities. The iterator yields pages of vulnerabilities. If Next returns an error, the next call to Next will retry the same page.

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	// Fixes is suggestions that tell you how to deal with this error.
	Fixes      []string    `json:"fixes"`
	Candidates []Candidate `json:"candidates,omitempty"`
}

Error is the error format returned by the v1 API.

func (*Error) Error

func (e *Error) Error() string

type HTTPError

type HTTPError int

HTTPError is the error indicated by HTTP status code.

func (HTTPError) Error

func (h HTTPError) Error() string

type License

type License struct {
	Types    []string `json:"types"`
	FilePath string   `json:"filePath"`
	Contents string   `json:"contents,omitempty"`
}

License is license metadata returned by package and module endpoints.

type Module

type Module struct {
	Path    string `json:"path"`
	Version string `json:"version"`
	// CommitTime is the timestamp returned by the module proxy's .info endpoint,
	// representing the time the version was created.
	CommitTime        time.Time `json:"commitTime"`
	IsLatest          bool      `json:"isLatest"`
	IsRedistributable bool      `json:"isRedistributable"`
	IsStandardLibrary bool      `json:"isStandardLibrary"`
	HasGoMod          bool      `json:"hasGoMod"`
	RepoURL           string    `json:"repoUrl"`
	GoModContents     string    `json:"goModContents,omitempty"`
	Readme            *Readme   `json:"readme,omitempty"`
	Licenses          []License `json:"licenses,omitempty"`
}

Module is the JSON response for /v1/module/.

type ModuleOptions

type ModuleOptions struct {
	Version  string
	Module   string
	Readme   bool
	Licenses bool
	Limit    int
	Token    string
	// Filter is a boolean Go expression used by list endpoints (versions,
	// vulns and packages) to filter the items in the response. Only items for
	// which the expression evaluates to true are returned.
	//
	// The available variables are the JSON field names of the items being
	// filtered, such as "path", "name" and "synopsis" for packages, the
	// ModuleVersion fields for versions, or "id", "summary" and "details" for
	// vulns. Built-in functions are contains, matches (regexp), hasPrefix and
	// hasSuffix. For example: `hasPrefix(path, "internal/")`.
	Filter string
	// PseudoVersions requests that pseudo-versions be included in the result.
	// By default, only tagged versions (release and prerelease) are returned.
	// This field applies only to the Versions and VersionsIter methods.
	PseudoVersions bool
}

ModuleOptions configures module-related requests.

type ModuleVersion

type ModuleVersion struct {
	ModulePath        string    `json:"modulePath"`
	Version           string    `json:"version"`
	CommitTime        time.Time `json:"commitTime"`
	IsRedistributable bool      `json:"isRedistributable"`
	HasGoMod          bool      `json:"hasGoMod"`
	LatestVersion     string    `json:"latestVersion"`
	Deprecated        bool      `json:"deprecated"`
	DeprecationReason string    `json:"deprecationReason"`
	Retracted         bool      `json:"retracted"`
	RetractionReason  string    `json:"retractionReason"`
}

ModuleVersion is a single version from /v1/versions/.

type Option

type Option func(*Client)

Option configures a Client.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient configures the HTTP client used for requests.

func WithServer

func WithServer(server string) Option

WithServer configures the pkgsite API server URL.

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent configures the HTTP User-Agent header.

type Package

type Package struct {
	Path              string    `json:"path"`
	Name              string    `json:"name"`
	ModulePath        string    `json:"modulePath"`
	Version           string    `json:"version"`
	Synopsis          string    `json:"synopsis"`
	IsRedistributable bool      `json:"isRedistributable"`
	IsStandardLibrary bool      `json:"isStandardLibrary"`
	IsLatest          bool      `json:"isLatest"`
	GOOS              string    `json:"goos"`
	GOARCH            string    `json:"goarch"`
	Docs              string    `json:"docs,omitempty"`
	Imports           []string  `json:"imports,omitempty"`
	Licenses          []License `json:"licenses,omitempty"`
}

Package is the JSON response for /v1/package/.

type PackageImportedBy

type PackageImportedBy struct {
	ModulePath string                    `json:"modulePath"`
	Version    string                    `json:"version"`
	ImportedBy PaginatedResponse[string] `json:"importedBy"`
}

PackageImportedBy is the response for /v1/imported-by/.

type PackageInfo

type PackageInfo struct {
	Path              string `json:"path"`
	Name              string `json:"name"`
	Synopsis          string `json:"synopsis"`
	IsRedistributable bool   `json:"isRedistributable"`
}

PackageInfo is package metadata returned by package list endpoints.

type PackageOptions

type PackageOptions struct {
	Version  string
	Module   string
	Doc      string
	Examples bool
	Imports  bool
	Licenses bool
	GOOS     string
	GOARCH   string
	Limit    int
	Token    string
	// Filter is a boolean Go expression used by list endpoints such as symbols
	// and imported-by to filter the items in the response. Only items for which
	// the expression evaluates to true are returned.
	//
	// The available variables are the JSON field names of the items being
	// filtered: for symbols, "name", "kind", "synopsis" and "parent"; for
	// imported-by, the import path is bound to "path". Built-in functions are
	// contains, matches (regexp), hasPrefix and hasSuffix. For example:
	// `contains(name, "Reader")` or `matches(path, "^golang.org/x/")`.
	Filter string
}

PackageOptions configures package-related requests.

type PackageSymbols

type PackageSymbols struct {
	ModulePath string                    `json:"modulePath"`
	Version    string                    `json:"version"`
	Symbols    PaginatedResponse[Symbol] `json:"symbols"`
}

PackageSymbols is the JSON response for /v1/symbols/.

type PackagesResponse

type PackagesResponse struct {
	ModulePath        string                         `json:"modulePath"`
	Version           string                         `json:"version"`
	IsStandardLibrary bool                           `json:"isStandardLibrary"`
	Packages          PaginatedResponse[PackageInfo] `json:"packages"`
}

PackagesResponse is the JSON response for /v1/packages/.

type PaginatedResponse

type PaginatedResponse[T any] struct {
	Items []T `json:"items"`
	// Total is the total number of items across all pages.
	// It may be -1 if the total is unknown, which can happen for the versions
	// endpoint when there is more than one page of results.
	Total         int    `json:"total"`
	NextPageToken string `json:"nextPageToken,omitempty"`
}

PaginatedResponse is a generic paginated response.

type Readme

type Readme struct {
	Filepath string `json:"filepath"`
	Contents string `json:"contents"`
}

Readme is README content returned by /v1/module/.

type SearchOptions

type SearchOptions struct {
	Symbol string
	Limit  int
	Token  string
	// Filter is a boolean Go expression used to filter the search results. Only
	// results for which the expression evaluates to true are returned.
	//
	// The available variables are the JSON field names of SearchResult:
	// "packagePath", "modulePath", "version" and "synopsis". Built-in functions
	// are contains, matches (regexp), hasPrefix and hasSuffix. For example:
	// `contains(synopsis, "logging")`.
	Filter string
}

SearchOptions configures search requests.

type SearchResult

type SearchResult struct {
	PackagePath string `json:"packagePath"`
	ModulePath  string `json:"modulePath"`
	Version     string `json:"version"`
	Synopsis    string `json:"synopsis"`
}

SearchResult is a single search result from /v1/search/.

type Symbol

type Symbol struct {
	Name     string `json:"name"`
	Kind     string `json:"kind"`
	Synopsis string `json:"synopsis"`
	Parent   string `json:"parent,omitempty"`
}

Symbol is a single symbol from /v1/symbols/.

type Vulnerability

type Vulnerability struct {
	ID           string `json:"id"`
	Summary      string `json:"summary"`
	Details      string `json:"details"`
	FixedVersion string `json:"fixedVersion"`
}

Vulnerability is a single vulnerability from /v1/vulns/.

Jump to

Keyboard shortcuts

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