Help us shape the future of Go! Take the 2026 Go Developer Survey

api

package
v0.23.0 Latest Latest
Warning

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

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

Documentation

Overview

Package api implements the Factorio MOD Portal and game download API clients.

See https://wiki.factorio.com/Mod_portal_API

Index

Constants

View Source
const (
	DefaultGameDownloadBaseURL = "https://www.factorio.com"
	DefaultGameAPIBaseURL      = "https://factorio.com"
)

Base URLs for the game download endpoints.

View Source
const DefaultPortalBaseURL = "https://mods.factorio.com"

DefaultPortalBaseURL is the MOD Portal endpoint.

Variables

View Source
var (
	ErrMODNotOnPortal  = errors.New("MOD not found on portal")
	ErrCredential      = errors.New("credential error")
	ErrInvalidArgument = errors.New("invalid argument")
	ErrInvalidResponse = errors.New("invalid API response")
)
View Source
var (
	Builds    = []string{"alpha", "expansion", "demo", "headless"}
	Platforms = []string{"win64", "win64-manual", "osx", "linux64"}
	Channels  = []string{"stable", "experimental"}
)

Valid build types, platforms, and release channels.

Functions

func LicenseIdentifiers

func LicenseIdentifiers() []string

LicenseIdentifiers returns the standard license identifiers.

func ValidLicenseIdentifier

func ValidLicenseIdentifier(value string) bool

ValidLicenseIdentifier reports whether the value is a standard or custom license identifier.

Types

type APICredential

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

APICredential is the API key required by the management API.

func LoadAPICredential

func LoadAPICredential() (APICredential, error)

LoadAPICredential loads the API key from FACTORIO_API_KEY.

func (APICredential) APIKey

func (c APICredential) APIKey() string

APIKey returns the API key.

func (APICredential) String

func (APICredential) String() string

type Category

type Category struct {
	Value       string
	Name        string
	Description string
}

Category is a MOD Portal category's display information.

See https://wiki.factorio.com/Mod_details_API#Category

func CategoryFor

func CategoryFor(value string) (Category, error)

CategoryFor returns the display Category for a raw API category value. Categories change rarely; an unrecognized value means this catalog is out of date and needs a code change, not a value to paper over, so this errors rather than degrading to a raw-string display (matching Ruby's Category.for, which raises KeyError for the same case).

type EditMetadata

type EditMetadata struct {
	Description string
	Summary     string
	Title       string
	Category    string
	Tags        []string
	License     string
	Homepage    string
	SourceURL   string
	FAQ         string
	Deprecated  *bool
}

EditMetadata is the metadata accepted by EditDetails. Only non-zero fields are sent; Deprecated needs the pointer to distinguish "unset" from "set to false".

type GameDownloadAPI

type GameDownloadAPI struct {
	Client          *httpx.Client
	Credentials     func() (ServiceCredential, error)
	Logger          *slog.Logger
	DownloadBaseURL string
	APIBaseURL      string
}

GameDownloadAPI talks to the game download endpoints.

See https://wiki.factorio.com/Download_API

func NewGameDownloadAPI

func NewGameDownloadAPI(client *httpx.Client, credentials func() (ServiceCredential, error), logger *slog.Logger) *GameDownloadAPI

NewGameDownloadAPI builds a game download client with the default URLs.

func (*GameDownloadAPI) DownloadURL

func (a *GameDownloadAPI) DownloadURL(version, build, platform string) (string, error)

DownloadURL builds the authenticated download URL for a game build; the download itself is performed by internal/transfer.

func (*GameDownloadAPI) GetLatestReleases

func (a *GameDownloadAPI) GetLatestReleases(ctx context.Context) (*LatestReleases, error)

GetLatestReleases fetches the latest release versions.

func (*GameDownloadAPI) LatestVersion

func (a *GameDownloadAPI) LatestVersion(ctx context.Context, channel, build string) (string, error)

LatestVersion returns the latest version for a channel and build, or "" when not available.

func (*GameDownloadAPI) ResolveFilename

func (a *GameDownloadAPI) ResolveFilename(ctx context.Context, version, build, platform string) (string, error)

ResolveFilename determines the download filename by following the redirect of a HEAD request and taking the final URL's basename.

type GetMODsOptions

type GetMODsOptions struct {
	Namelist       []string
	HideDeprecated *bool
	Page           int    // 0 = unset
	PageSize       string // "", a positive integer, or "max"
	Sort           string // "", name, created_at, updated_at
	SortOrder      string // "", asc, desc
	Version        string // "", or a Factorio version like "2.0"
}

GetMODsOptions filters and pages the MOD list.

type Image

type Image struct {
	ID        string `json:"id"`
	Thumbnail string `json:"thumbnail"`
	URL       string `json:"url"`
}

Image is one entry of a MOD's image gallery.

type LatestReleases

type LatestReleases struct {
	Stable       map[string]string `json:"stable"`
	Experimental map[string]string `json:"experimental"`
}

LatestReleases is the /api/latest-releases response: version strings per build, per channel.

type License

type License struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Title       string `json:"title"`
	Description string `json:"description"`
	URL         string `json:"url"`
}

License describes a MOD license.

func StandardLicenseFor added in v0.21.0

func StandardLicenseFor(id string) (license License, ok bool)

StandardLicenseFor returns the catalog entry for a standard license identifier. ok is false for custom or unrecognized identifiers.

func StandardLicenses added in v0.21.0

func StandardLicenses() []License

StandardLicenses returns the catalog of standard licenses, ordered as in LicenseIdentifiers.

type MODDownloadAPI

type MODDownloadAPI struct {
	Credentials func() (ServiceCredential, error)
	BaseURL     string
}

MODDownloadAPI builds authenticated MOD download URLs. Credentials are resolved lazily so the environment is only consulted when a download actually happens; the download itself is performed by internal/transfer.

func NewMODDownloadAPI

func NewMODDownloadAPI(credentials func() (ServiceCredential, error)) *MODDownloadAPI

NewMODDownloadAPI builds a download-URL builder with the default base URL.

func (*MODDownloadAPI) DownloadURL

func (a *MODDownloadAPI) DownloadURL(downloadPath string) (string, error)

DownloadURL turns a relative download path from a Release into a full URL with the username/token credentials attached.

type MODInfo

type MODInfo struct {
	Name           string    `json:"name"`
	Title          string    `json:"title"`
	Owner          string    `json:"owner"`
	Summary        string    `json:"summary"`
	DownloadsCount int       `json:"downloads_count"`
	Category       string    `json:"category"`
	Score          float64   `json:"score"`
	Thumbnail      string    `json:"thumbnail"` // relative asset path
	LatestRelease  *Release  `json:"latest_release"`
	Releases       []Release `json:"releases"`

	Changelog         string    `json:"changelog"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
	LastHighlightedAt time.Time `json:"last_highlighted_at"`
	Description       string    `json:"description"`
	SourceURL         string    `json:"source_url"`
	Homepage          string    `json:"homepage"`
	FAQ               string    `json:"faq"`
	Tags              []string  `json:"tags"`
	License           *License  `json:"license"`
	Images            []Image   `json:"images"`
	Deprecated        bool      `json:"deprecated"`
}

MODInfo is MOD metadata from the portal. The detail fields (Changelog through Deprecated) are only populated by the full endpoint.

func (*MODInfo) ThumbnailURL

func (m *MODInfo) ThumbnailURL() string

ThumbnailURL returns the absolute thumbnail URL, or "" when absent.

func (*MODInfo) UnmarshalJSON

func (m *MODInfo) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes MOD info. LastHighlightedAt gets its own pass: the Portal represents it as either a full RFC3339 timestamp or a bare "2006-01-02" date — both valid ISO 8601, but only the former is valid RFC3339, which is all time.Time's own UnmarshalJSON accepts. CreatedAt/UpdatedAt are always full timestamps in observed Portal responses and keep the standard time.Time decoding.

type MODManagementAPI

type MODManagementAPI struct {
	Client   *httpx.Client
	Uploader Uploader
	Logger   *slog.Logger
	BaseURL  string
	// Credentials resolves the API key lazily so FACTORIO_API_KEY is only
	// required when a management operation actually runs.
	Credentials func() (APICredential, error)
	// OnMODChanged is invoked with the MOD name after any operation that
	// changes the MOD on the portal; wired to MODPortalAPI's cache
	// invalidation. This replaces the Ruby dry-events subscription.
	OnMODChanged func(ctx context.Context, name string)
}

MODManagementAPI performs portal operations that require an API key: publishing, uploading releases, editing details and images.

See https://wiki.factorio.com/Mod_upload_API

func NewMODManagementAPI

func NewMODManagementAPI(client *httpx.Client, uploader Uploader, credentials func() (APICredential, error), logger *slog.Logger) *MODManagementAPI

NewMODManagementAPI builds a management client with the default base URL.

func (*MODManagementAPI) EditDetails

func (a *MODManagementAPI) EditDetails(ctx context.Context, name string, metadata EditMetadata) error

EditDetails updates a MOD's metadata on the portal.

func (*MODManagementAPI) EditImages

func (a *MODManagementAPI) EditImages(ctx context.Context, name string, imageIDs []string) error

EditImages replaces the MOD's image list with the given IDs, in order.

func (*MODManagementAPI) FinishImageUpload

func (a *MODManagementAPI) FinishImageUpload(ctx context.Context, name, uploadURL, imagePath string) (Image, error)

FinishImageUpload uploads the image to the URL from InitImageUpload and returns the created image.

func (*MODManagementAPI) FinishUpload

func (a *MODManagementAPI) FinishUpload(ctx context.Context, name, uploadURL, filePath string, metadata map[string]string) error

FinishUpload uploads the MOD file to the URL from InitPublish/InitUpload. metadata is only meaningful for the publish scenario.

func (*MODManagementAPI) InitImageUpload

func (a *MODManagementAPI) InitImageUpload(ctx context.Context, name string) (string, error)

InitImageUpload starts an image upload and returns the upload URL.

func (*MODManagementAPI) InitPublish

func (a *MODManagementAPI) InitPublish(ctx context.Context, name string) (string, error)

InitPublish starts publication of a brand-new MOD and returns the upload URL.

func (*MODManagementAPI) InitUpload

func (a *MODManagementAPI) InitUpload(ctx context.Context, name string) (string, error)

InitUpload starts a release upload to an existing MOD and returns the upload URL.

type MODPortalAPI

type MODPortalAPI struct {
	Client  *httpx.Client
	Cache   cache.Cache
	Logger  *slog.Logger
	BaseURL string
}

MODPortalAPI retrieves MOD lists and details. No authentication is required; response caching is provided by the client's CacheTransport, and Cache is used to invalidate entries after portal-changing operations.

func NewMODPortalAPI

func NewMODPortalAPI(client *httpx.Client, apiCache cache.Cache, logger *slog.Logger) *MODPortalAPI

NewMODPortalAPI builds a portal client with the default base URL.

func (*MODPortalAPI) GetMOD

func (a *MODPortalAPI) GetMOD(ctx context.Context, name string) (*MODInfo, error)

GetMOD retrieves basic information for a MOD (the short endpoint).

func (*MODPortalAPI) GetMODFull

func (a *MODPortalAPI) GetMODFull(ctx context.Context, name string) (*MODInfo, error)

GetMODFull retrieves full information for a MOD, including the detail fields and the full Releases list. Confirmed against the live API: MODInfo.LatestRelease is nil in this response (the Portal API wiki never documents this, or how "latest" would even be chosen) — callers that need a "latest" release must derive it from Releases themselves.

func (*MODPortalAPI) GetMODs

func (a *MODPortalAPI) GetMODs(ctx context.Context, opts GetMODsOptions) (*MODsPage, error)

GetMODs retrieves one page of the MOD list.

func (*MODPortalAPI) InvalidateMODCache

func (a *MODPortalAPI) InvalidateMODCache(ctx context.Context, name string) error

InvalidateMODCache removes the cached short and full responses for a MOD, typically after it changed on the portal. Wired as MODManagementAPI's OnMODChanged callback.

type MODsPage

type MODsPage struct {
	Results    []MODInfo  `json:"results"`
	Pagination Pagination `json:"pagination"`
}

MODsPage is one page of a MOD list response.

type Pagination

type Pagination struct {
	Count     int `json:"count"`
	Page      int `json:"page"`
	PageCount int `json:"page_count"`
	PageSize  int `json:"page_size"`
}

Pagination describes the paging of a MOD list response.

type Release

type Release struct {
	DownloadURL  string          `json:"download_url"` // relative path
	FileName     string          `json:"file_name"`
	InfoJSON     ReleaseInfoJSON `json:"info_json"`
	ReleasedAt   time.Time       `json:"released_at"`
	Version      mod.MODVersion  `json:"-"`
	SHA1         string          `json:"sha1"`
	FeatureFlags []string        `json:"feature_flags"`
	// contains filtered or unexported fields
}

Release is one version of a MOD published on the portal.

func (*Release) UnmarshalJSON

func (r *Release) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a release, tolerating out-of-range version strings so a single odd release does not fail the whole MOD.

type ReleaseInfoJSON

type ReleaseInfoJSON struct {
	FactorioVersion string   `json:"factorio_version"`
	Dependencies    []string `json:"dependencies"`
}

ReleaseInfoJSON is the subset of info.json the portal includes per release.

type ServiceCredential

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

ServiceCredential is the username/token pair used by the download endpoints. Fields are unexported so the values do not leak through formatting; String renders masked.

func LoadServiceCredential

func LoadServiceCredential(playerDataPath string) (ServiceCredential, error)

LoadServiceCredential loads the username/token pair from the environment (FACTORIO_USERNAME / FACTORIO_TOKEN), falling back to player-data.json at the given path when neither is set. Setting only one variable is an error.

func (ServiceCredential) String

func (ServiceCredential) String() string

func (ServiceCredential) Token

func (c ServiceCredential) Token() string

Token returns the service token.

func (ServiceCredential) Username

func (c ServiceCredential) Username() string

Username returns the service username.

type Uploader

type Uploader interface {
	Upload(ctx context.Context, uploadURL, filePath string, fields map[string]string, fieldName string) ([]byte, error)
}

Uploader performs multipart file uploads; implemented by internal/transfer in Phase 8. fields are extra form fields, fieldName is the file's form field (defaults to "file" when empty).

Jump to

Keyboard shortcuts

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