frontend

package
v0.0.0-...-86cb477 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2024 License: BSD-3-Clause Imports: 58 Imported by: 0

Documentation

Overview

Package frontend provides functionality for running the pkg.go.dev site.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TagRoute

func TagRoute(route string, r *http.Request) string

TagRoute categorizes incoming requests to the frontend for use in monitoring.

Types

type BadgePage

type BadgePage struct {
	page.BasePage
	// LinkPath is the URL path of the badge will link to.
	LinkPath string
	// BadgePath is the URL path of the badge SVG.
	BadgePath string
}

type Cacher

type Cacher interface {
	// Cache returns a new middleware that caches every request.
	// The name of the cache is used only for metrics.
	// The expirer is a func that is used to map a new request to its TTL.
	// authHeader is the header key used by the cache to know that a
	// request should bypass the cache.
	// authValues is the set of values that could be set on the authHeader in
	// order to bypass the cache.
	Cache(name string, expirer func(r *http.Request) time.Duration, authValues []string) func(http.Handler) http.Handler
}

A Cacher is used to create request caches for http handlers.

type Directory

type Directory struct {
	// Prefix is the prefix of the unit path for the subdirectories.
	Prefix string

	// Root is the package located at prefix, nil for a directory.
	Root *DirectoryInfo

	// Subdirectories contains subdirectories with prefix trimmed from their suffix.
	Subdirectories []*DirectoryInfo
}

Directory is either a nested module or subdirectory of a unit, organized in a two level tree structure. This content is used in the directories section of the unit page.

type DirectoryInfo

type DirectoryInfo struct {
	Suffix     string
	URL        string
	Synopsis   string
	IsModule   bool
	IsInternal bool
}

DirectoryInfo contains information about a package or nested module, relative to the path of a given unit. This content is used in the Directories section of the unit page.

type FetchServerInterface

type FetchServerInterface interface {
	ServeFetch(w http.ResponseWriter, r *http.Request, ds internal.DataSource) (err error)
	ServePathNotFoundPage(w http.ResponseWriter, r *http.Request,
		ds internal.PostgresDB, fullPath, modulePath, requestedVersion string) (err error)
}

FetchServerInterface is an interface for the parts of the server that support adding packages to a queue for fetching by a worker server. TODO(matloob): rename to FetchServer once the FetchServer type moves to its own package

type File

type File struct {
	Name string
	URL  string
}

File is a source file for a package.

type Heading

type Heading struct {
	// Level is the original level of the heading.
	Level int
	// Text is the content from the readme contained within a heading.
	Text string
	// ID corresponds to the ID attribute for a heading element
	// and is also used in an href to the corresponding section
	// within the readme outline. All ids are prefixed with readme-
	// to avoid name collisions.
	ID string
	// Children are nested headings.
	Children []*Heading
	// contains filtered or unexported fields
}

Heading holds data about a heading and nested headings within a readme. This data is used in the sidebar template to render the readme outline.

type Homepage

type Homepage struct {
	page.BasePage

	// TipIndex is the index of the initial search tip to render.
	TipIndex int

	// SearchTips is a collection of search tips to show on the homepage.
	SearchTips []searchTip

	// LocalModules holds locally-hosted modules, for quick navigation.
	// Empty in production.
	LocalModules []LocalModule
}

Homepage contains fields used in rendering the homepage template.

type ImportedByDetails

type ImportedByDetails struct {
	// ModulePath is the module path for the package referenced on this page.
	ModulePath string

	// ImportedBy is the collection of packages that import the
	// given package and are not part of the same module.
	// They are organized into a tree of sections by prefix.
	ImportedBy []*Section

	// NumImportedByDisplay is the display text at the top of the imported by
	// tab section, which shows the imported by count and package limit.
	NumImportedByDisplay string

	// Total is the total number of importers.
	Total int
}

ImportedByDetails contains information for the collection of packages that import a given package.

type ImportsDetails

type ImportsDetails struct {
	ModulePath string

	// ExternalImports is the collection of package imports that are not in
	// the Go standard library and are not part of the same module
	ExternalImports []string

	// InternalImports is an array of packages representing the package's
	// imports that are part of the same module.
	InternalImports []string

	// StdLib is an array of packages representing the package's imports
	// that are in the Go standard library.
	StdLib []string
}

ImportsDetails contains information for a package's imports.

type License

type License struct {
	*licenses.License
	Anchor safehtml.Identifier
	Source string
}

License contains information used for a single license section.

type LicenseMetadata

type LicenseMetadata struct {
	Type   string
	Anchor safehtml.Identifier
}

LicenseMetadata contains license metadata that is used in the package header.

type LicensePolicyPage

type LicensePolicyPage struct {
	pagepkg.BasePage
	LicenseFileNames []string
	LicenseTypes     []licenses.AcceptedLicenseInfo
}

LicensePolicyPage is used to generate the static license policy page.

type LicensesDetails

type LicensesDetails struct {
	IsRedistributable bool
	Licenses          []License
}

LicensesDetails contains license information for a package or module.

type LocalModule

type LocalModule struct {
	ModulePath string `json:"Path"`
	Dir        string `json:"Dir"`
}

LocalModule holds information about a locally-hosted module.

JSON-compatible with `go list` output.

type MainDetails

type MainDetails struct {
	// Directories are packages and nested modules relative to the path for the
	// unit.
	Directories []*Directory

	// Licenses contains license metadata used in the header.
	Licenses []LicenseMetadata

	// NumImports is the number of imports for the package.
	NumImports string

	// CommitTime is time that this version was published, or the time that
	// has elapsed since this version was committed if it was done so recently.
	CommitTime string

	// Readme is the rendered readme HTML.
	Readme safehtml.HTML

	// ReadmeOutline is a collection of headings from the readme file
	// used to render the readme outline in the sidebar.
	ReadmeOutline []*Heading

	// ReadmeLinks are from the "Links" section of this unit's readme file, and
	// are displayed on the right sidebar.
	ReadmeLinks []link

	// DocLinks are from the "Links" section of the Go package documentation,
	// and are displayed on the right sidebar.
	DocLinks []link

	// ModuleReadmeLinks are from the "Links" section of this unit's module, if
	// the unit is not itself a module. They are displayed on the right sidebar.
	// See https://golang.org/issue/42968.
	ModuleReadmeLinks []link

	// ImportedByCount is the number of packages that import this path.
	// When the count is > limit it will read as 'limit+'. This field
	// is not supported when using a datasource proxy.
	ImportedByCount string

	DocBody       safehtml.HTML
	DocOutline    safehtml.HTML
	MobileOutline safehtml.HTML
	IsPackage     bool

	// DocSynopsis is used as the content for the <meta name="Description">
	// tag on the main unit page.
	DocSynopsis string

	// GOOS and GOARCH are the build context for the doc.
	GOOS, GOARCH string

	// BuildContexts holds the values for build contexts available for the doc.
	BuildContexts []internal.BuildContext

	// SourceFiles contains .go files for the package.
	SourceFiles []*File

	// RepositoryURL is the URL to the repository containing the package.
	RepositoryURL string

	// SourceURL is the URL to the source of the package.
	SourceURL string

	// ExpandReadme is holds the expandable readme state.
	ExpandReadme bool

	// ModFileURL is an URL to the mod file.
	ModFileURL string

	// IsTaggedVersion is true if the version is not a psuedorelease.
	IsTaggedVersion bool

	// IsStableVersion is true if the major version is v1 or greater.
	IsStableVersion bool

	// IsRedistributable is whether the unit is redistributable.
	IsRedistributable bool
}

MainDetails contains data needed to render the unit template.

type Readme

type Readme struct {
	HTML    safehtml.HTML // rendered HTML
	Outline []*Heading    // document headings
	Links   []link        // links from the "Links" section
}

Readme holds the result of processing a REAME file.

func ProcessReadme

func ProcessReadme(ctx context.Context, u *internal.Unit) (_ *Readme, err error)

ProcessReadme processes the README of unit u, if it has one. Processing includes rendering and sanitizing the HTML or Markdown, and extracting headings and links.

Headings are prefixed with "readme-" and heading levels are adjusted to start at h3 in order to nest them properly within the rest of the page. The readme's original styling is preserved in the html by giving headings a css class styled identical to their original heading level.

The extracted links are for display outside of the readme contents.

This function is exported for use by external tools.

type SearchPage

type SearchPage struct {
	pagepkg.BasePage

	// PackageTabQuery is the search query, stripped of any filters.
	// This is used if the user clicks on the package tab.
	PackageTabQuery string

	Pagination pagination
	Results    []*SearchResult
}

SearchPage contains all of the data that the search template needs to populate.

type SearchResult

type SearchResult struct {
	Name           string
	PackagePath    string
	ModulePath     string
	Version        string
	ChipText       string
	Synopsis       string
	DisplayVersion string
	Licenses       []string
	CommitTime     string
	NumImportedBy  string
	Symbols        *subResult
	SameModule     *subResult // package paths in the same module
	OtherMajor     *subResult // package paths in lower major versions
	SymbolName     string
	SymbolKind     string
	SymbolSynopsis string
	SymbolGOOS     string
	SymbolGOARCH   string
	SymbolLink     string
	Vulns          []vuln.Vuln
}

SearchResult contains data needed to display a single search result.

type Section

type Section struct {
	Prefix   string     // prefix for this section, or if Subs==nil, a single line
	Subs     []*Section // subsections
	NumLines int        // total number of lines in subsections
}

A Section represents a collection of lines with a common prefix. The collection is itself divided into sections by prefix, forming a tree.

func Sections

func Sections(lines []string, nextPrefix prefixFunc) []*Section

Sections transforms a list of lines, which must be sorted, into a list of Sections. Each Section in the result contains all the contiguous lines with the same prefix.

The nextPrefix function is responsible for extracting prefixes from lines.

type Server

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

Server can be installed to serve the go discovery frontend.

func NewServer

func NewServer(scfg ServerConfig) (_ *Server, err error)

NewServer creates a new Server for the given database and template directory.

func (*Server) GetLatestInfo

func (s *Server) GetLatestInfo(ctx context.Context, unitPath, modulePath string, latestUnitMeta *internal.UnitMeta) internal.LatestInfo

GetLatestInfo returns various pieces of information about the latest versions of a unit and module:

  • The linkable form of the minor version of the unit.
  • The latest module path and the full unit path of any major version found given the fullPath and the modulePath.

It returns empty strings on error. It is intended to be used as an argument to middleware.LatestVersions.

func (*Server) Install

func (s *Server) Install(handle func(string, http.Handler), cacher Cacher, authValues []string)

Install registers server routes using the given handler registration func. authValues is the set of values that can be set on authHeader to bypass the cache.

func (*Server) InstallFS

func (s *Server) InstallFS(path string, fsys fs.FS)

InstallFS adds path under the /files handler, serving the files in fsys.

func (*Server) PanicHandler

func (s *Server) PanicHandler() (_ http.HandlerFunc, err error)

PanicHandler returns an http.HandlerFunc that can be used in HTTP middleware. It returns an error if something goes wrong pre-rendering the error template.

type ServerConfig

type ServerConfig struct {
	Config *config.Config
	// Note that FetchServer may be nil.
	FetchServer FetchServerInterface
	// DataSourceGetter should return a DataSource on each call.
	// It should be goroutine-safe.
	DataSourceGetter  func(context.Context) internal.DataSource
	Queue             queue.Queue
	TemplateFS        template.TrustedFS // for loading templates safely
	StaticFS          fs.FS              // for static/ directory
	ThirdPartyFS      fs.FS              // for third_party/ directory
	DevMode           bool
	LocalMode         bool
	LocalModules      []LocalModule
	Reporter          derrors.Reporter
	VulndbClient      *vuln.Client
	DepsDevHTTPClient *http.Client
}

ServerConfig contains everything needed by a Server.

type StyleSection

type StyleSection struct {
	// ID is the ID for the header element of the section.
	ID string

	// Title is the title of the section, taken from the name
	// of the markdown file.
	Title string

	// Content is the HTML rendered from the parsed markdown file.
	Content safehtml.HTML

	// Outline is a collection of headings used in the navigation.
	Outline []*Heading
}

StyleSection represents a section on the styleguide page.

type TabSettings

type TabSettings struct {
	// Name is the tab name used in the URL.
	Name string

	// DisplayName is the formatted tab name.
	DisplayName string

	// AlwaysShowDetails defines whether the tab content can be shown even if the
	// package is not determined to be redistributable.
	AlwaysShowDetails bool

	// TemplateName is the name of the template used to render the
	// corresponding tab, as defined in Server.templates.
	TemplateName string

	// Disabled indicates whether a tab should be displayed as disabled.
	Disabled bool
}

TabSettings defines tab-specific metadata.

type UnitPage

type UnitPage struct {
	page.BasePage
	// Unit is the unit for this page.
	Unit *internal.UnitMeta

	// Breadcrumb contains data used to render breadcrumb UI elements.
	Breadcrumb breadcrumb

	// Title is the title of the page.
	Title string

	// URLPath is the path suitable for links on the page.
	// See the unitURLPath for details.
	URLPath string

	// CanonicalURLPath is a permanent representation of the URL path for a
	// unit.
	// It uses the resolved module path and version.
	// For example, if the latest version of /my.module/pkg is version v1.5.2,
	// the canonical URL path for that unit would be /my.module@v1.5.2/pkg
	CanonicalURLPath string

	// The version string formatted for display.
	DisplayVersion string

	// LinkVersion is version string suitable for links used to compute
	// latest badges.
	LinkVersion string

	// LatestURL is a url pointing to the latest version of a unit.
	LatestURL string

	// IsLatestMinor is true if the version displayed is the latest minor of the unit.
	// Used to determine the canonical URL for search engines and robots meta directives.
	IsLatestMinor bool

	// LatestMinorClass is the CSS class that describes the current unit's minor
	// version in relationship to the latest version of the unit.
	LatestMinorClass string

	// Information about the latest major version of the module.
	LatestMajorVersion    string
	LatestMajorVersionURL string

	// PageType is the type of page (pkg, cmd, dir, std, or mod).
	PageType string

	// PageLabels are the labels that will be displayed
	// for a given page.
	PageLabels []string

	// CanShowDetails indicates whether details can be shown or must be
	// hidden due to issues like license restrictions.
	CanShowDetails bool

	// Settings contains settings for the selected tab.
	SelectedTab TabSettings

	// RedirectedFromPath is the path that redirected to the current page.
	// If non-empty, a "redirected from" banner will be displayed
	// (see static/frontend/unit/_header.tmpl).
	RedirectedFromPath string

	// Details contains data specific to the type of page being rendered.
	Details any

	// Vulns holds vulnerability information.
	Vulns []vuln.Vuln

	// DepsDevURL holds the full URL to this module version on deps.dev.
	DepsDevURL string

	// IsGoProject is true if the package is from the standard library or a
	// golang.org sub-repository.
	IsGoProject bool
}

UnitPage contains data needed to render the unit template.

type VulnEntryPage

type VulnEntryPage struct {
	page.BasePage
	Entry            *osv.Entry
	AffectedPackages []*vuln.AffectedPackage
	AliasLinks       []link
	AdvisoryLinks    []link
}

VulnEntryPage holds the information for a page that displays a single vuln entry.

type VulnListPage

type VulnListPage struct {
	page.BasePage
	Entries []*osv.Entry
}

VulnListPage holds the information for a page that lists vuln entries.

Directories

Path Synopsis
Package client provides a client for interacting with the frontend.
Package client provides a client for interacting with the frontend.
Package page defines common fields shared by pages when rendering templages.
Package page defines common fields shared by pages when rendering templages.
serrors contains error types used by the server
serrors contains error types used by the server
Package urlinfo provides functions for extracting information out of url paths.
Package urlinfo provides functions for extracting information out of url paths.

Jump to

Keyboard shortcuts

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