Documentation
¶
Overview ¶
Package serverlist implements Steam's unofficial GetServerList Web API.
Index ¶
- Constants
- Variables
- func NewHandler(provider Provider, opts ...HandlerOption) http.Handler
- type APIError
- type Client
- func (c *Client) Collect(ctx context.Context, plan DiscoveryPlan, options CollectOptions) (Result[Server], error)
- func (c *Client) CollectAddresses(ctx context.Context, plan DiscoveryPlan, options CollectOptions) (Result[netip.AddrPort], error)
- func (c *Client) CollectLite(ctx context.Context, plan DiscoveryPlan, options CollectOptions) (Result[ServerLite], error)
- func (c *Client) Discover(ctx context.Context, root QueryFilter, options DiscoveryOptions) (DiscoveryResult[Server], error)
- func (c *Client) DiscoverAddresses(ctx context.Context, root QueryFilter, options DiscoveryOptions) (DiscoveryResult[netip.AddrPort], error)
- func (c *Client) DiscoverLite(ctx context.Context, root QueryFilter, options DiscoveryOptions) (DiscoveryResult[ServerLite], error)
- func (c *Client) List(ctx context.Context, query ListQuery) (Servers, error)
- func (c *Client) ListAddresses(ctx context.Context, query ListQuery) ([]netip.AddrPort, error)
- func (c *Client) ListLite(ctx context.Context, query ListQuery) ([]ServerLite, error)
- type CollectOptions
- type DiscoveryEvent
- type DiscoveryMismatch
- type DiscoveryOptions
- type DiscoveryPlan
- type DiscoveryReasons
- type DiscoveryResult
- type DiscoveryStatus
- type Filter
- func (f *Filter) Add(key FilterKey, value string)
- func (f *Filter) AddNand(key FilterKey, value string)
- func (f *Filter) AddNor(key FilterKey, value string)
- func (f *Filter) Clone() *Filter
- func (f *Filter) Remove(key FilterKey, value string)
- func (f *Filter) RemoveNand(key FilterKey, value string)
- func (f *Filter) RemoveNor(key FilterKey, value string)
- func (f *Filter) String() (string, error)
- type FilterKey
- type GroupKind
- type HTTPError
- type HandlerOption
- type ListQuery
- type Option
- type Predicate
- type PredicateGroup
- type Provider
- type ProviderFunc
- type QueryFilter
- type Result
- type Server
- type ServerLite
- type Servers
- type SplitFeature
Examples ¶
Constants ¶
const DefaultLimit uint32 = 10000
DefaultLimit is the default maximum number of records requested by the compatible HTTP handler when the query omits limit.
Variables ¶
var ( // ErrNilContext indicates an operation received a nil context. ErrNilContext = errors.New("web API context is nil") // ErrClientUninitialized indicates the client is nil or lacks required configuration. ErrClientUninitialized = errors.New("web API client is nil or uninitialized") // ErrConfigureClient marks failures applying client options. ErrConfigureClient = errors.New("configure Web API client") // ErrCreateRequest marks failures constructing the HTTP request. ErrCreateRequest = errors.New("create Web API request") // ErrExecuteRequest marks transport failures executing the HTTP request. ErrExecuteRequest = errors.New("execute Web API request") // ErrReadResponseBody marks failures reading an HTTP response body. ErrReadResponseBody = errors.New("read Web API response") // ErrResponseTooLarge indicates the response body exceeded its configured bound. ErrResponseTooLarge = errors.New("web API response exceeds configured size limit") // ErrDecodeResponse marks failures decoding the top-level JSON document. ErrDecodeResponse = errors.New("decode Web API response") // ErrMissingResponseEnvelope indicates the API response object is absent or null. ErrMissingResponseEnvelope = errors.New("web API response envelope is missing response") // ErrDecodeServerList marks failures decoding the servers array. ErrDecodeServerList = errors.New("decode Web API servers") // ErrDecodeServerRecord marks failures decoding one server record. ErrDecodeServerRecord = errors.New("decode Web API server") // ErrInvalidServerAddress indicates a record's address is not a valid endpoint. ErrInvalidServerAddress = errors.New("invalid server address") // ErrInvalidSteamID indicates a Steam ID is absent or not an unsigned decimal integer. ErrInvalidSteamID = errors.New("invalid steamid") // ErrInvalidAPIErrorCode indicates an API error code has an unsupported JSON value. ErrInvalidAPIErrorCode = errors.New("invalid API error code") // ErrNilHTTPClient indicates [WithHTTPClient] received nil. ErrNilHTTPClient = errors.New("HTTP client is nil") // ErrInvalidBaseURL indicates the configured endpoint is not an absolute HTTP URL. ErrInvalidBaseURL = errors.New("invalid Web API base URL") // ErrUnsupportedBaseURLScheme indicates the endpoint is not HTTP or HTTPS. ErrUnsupportedBaseURLScheme = errors.New("unsupported Web API base URL scheme") // ErrMaxResponseSizeMustBePositive indicates a non-positive response body limit. ErrMaxResponseSizeMustBePositive = errors.New("maximum response size must be positive") // ErrMaxResponseSizeOverflows indicates the configured size cannot be incremented safely. ErrMaxResponseSizeOverflows = errors.New("maximum response size is too large") // ErrNilProvider indicates the HTTP handler has no provider configured. ErrNilProvider = errors.New("provider is not configured") // ErrMethodNotAllowed identifies requests using an unsupported HTTP method. ErrMethodNotAllowed = errors.New("method not allowed") // ErrInvalidAPIKey identifies requests rejected by handler key validation. ErrInvalidAPIKey = errors.New("invalid API key") // ErrProviderFailure identifies a provider error returned as an HTTP response. ErrProviderFailure = errors.New("provider error") // ErrInvalidListLimit indicates the limit is not an unsigned 32-bit integer. ErrInvalidListLimit = errors.New("invalid limit") // ErrListLimitExceedsMaximum indicates the requested limit exceeds handler policy. ErrListLimitExceedsMaximum = errors.New("limit exceeds maximum") // ErrFilterCannotCombineNORAndNAND indicates incompatible exclusion groups. ErrFilterCannotCombineNORAndNAND = errors.New("filter cannot combine NOR and NAND conditions") // ErrInvalidDiscoveryOptions indicates invalid discovery limits or features. ErrInvalidDiscoveryOptions = errors.New("invalid discovery options") // ErrInvalidDiscoveryPlan indicates an unsupported or malformed saved plan. ErrInvalidDiscoveryPlan = errors.New("invalid discovery plan") // ErrInvalidQueryFilter indicates a validated filter contains malformed data. ErrInvalidQueryFilter = errors.New("invalid validated server filter") // ErrConflictingQueryFilter indicates predicates cannot match simultaneously. ErrConflictingQueryFilter = errors.New("conflicting server filter predicates") // ErrDiscoveryResponseOverLimit indicates the endpoint returned more rows than requested. ErrDiscoveryResponseOverLimit = errors.New("discovery response exceeds requested row limit") // ErrUnsupportedDiscoveryFilter indicates valid filter syntax outside the partition engine's subset. ErrUnsupportedDiscoveryFilter = errors.New("unsupported discovery filter expression") // ErrInvalidJSONBoolean indicates a projected Web API boolean field was neither true, false, nor null. ErrInvalidJSONBoolean = errors.New("invalid JSON boolean value") )
Functions ¶
func NewHandler ¶
func NewHandler(provider Provider, opts ...HandlerOption) http.Handler
NewHandler exposes the supported GetServerList response shape over HTTP.
Types ¶
type APIError ¶
type APIError struct {
// Code is Steam's API error code, normalized to a decimal or textual string.
Code string `json:"errorcode,omitempty"`
// Description is the human-readable error detail returned by the API.
Description string `json:"errordesc,omitempty"`
}
APIError reports an error returned in the Steam API response envelope.
func (*APIError) UnmarshalJSON ¶
UnmarshalJSON accepts Steam responses that encode errorcode as either a JSON string or a number.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a stateless Steam Web API client safe for concurrent use.
func (*Client) Collect ¶
func (c *Client) Collect( ctx context.Context, plan DiscoveryPlan, options CollectOptions, ) (Result[Server], error)
Collect executes the active leaves of a saved plan and returns rich records.
func (*Client) CollectAddresses ¶
func (c *Client) CollectAddresses( ctx context.Context, plan DiscoveryPlan, options CollectOptions, ) (Result[netip.AddrPort], error)
CollectAddresses executes a saved plan and returns unique endpoints.
func (*Client) CollectLite ¶
func (c *Client) CollectLite( ctx context.Context, plan DiscoveryPlan, options CollectOptions, ) (Result[ServerLite], error)
CollectLite executes a saved plan and returns compact records.
func (*Client) Discover ¶
func (c *Client) Discover( ctx context.Context, root QueryFilter, options DiscoveryOptions, ) (DiscoveryResult[Server], error)
Discover queries a filter and builds a reusable bounded partition plan.
func (*Client) DiscoverAddresses ¶
func (c *Client) DiscoverAddresses( ctx context.Context, root QueryFilter, options DiscoveryOptions, ) (DiscoveryResult[netip.AddrPort], error)
DiscoverAddresses queries a filter and returns unique endpoints and a reusable plan.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
slist "github.com/woozymasta/steamserverlist"
)
func main() {
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = fmt.Fprint(w, `{"response":{"servers":[
{"addr":"192.0.2.1:27015","appid":221100},
{"addr":"192.0.2.2:27015","appid":221100}
]}}`)
}))
defer api.Close()
client, err := slist.New("example-api-key", slist.WithBaseURL(api.URL))
if err != nil {
panic(err)
}
filter, err := slist.NewQueryFilter(
[]slist.Predicate{{Key: slist.KeyAppID, Value: "221100"}},
nil,
)
if err != nil {
panic(err)
}
discovery, err := client.DiscoverAddresses(
context.Background(),
filter,
slist.DiscoveryOptions{},
)
if err != nil {
panic(err)
}
fmt.Printf("Found %d server addresses:\n", len(discovery.Items))
for _, address := range discovery.Items {
fmt.Println(address)
}
fmt.Printf("All query branches drained: %t\n", discovery.Status.Complete())
}
Output: Found 2 server addresses: 192.0.2.1:27015 192.0.2.2:27015 All query branches drained: true
func (*Client) DiscoverLite ¶
func (c *Client) DiscoverLite( ctx context.Context, root QueryFilter, options DiscoveryOptions, ) (DiscoveryResult[ServerLite], error)
DiscoverLite queries a filter and returns compact records and a reusable plan.
func (*Client) List ¶
List retrieves rich server records from GetServerList.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
slist "github.com/woozymasta/steamserverlist"
)
func main() {
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
if query.Get("filter") != `\appid\221100\secure\1` || query.Get("limit") != "100" {
http.Error(w, "unexpected query", http.StatusBadRequest)
return
}
_, _ = fmt.Fprint(w, `{
"response":{
"servers":[{
"addr":"192.0.2.1:27015",
"name":"Example DayZ server",
"players":3,
"max_players":60,
"gametype":"battleye, lqs0"
}]
}
}`)
}))
defer api.Close()
client, err := slist.New("example-api-key", slist.WithBaseURL(api.URL))
if err != nil {
panic(err)
}
servers, err := client.List(context.Background(), slist.ListQuery{
Filter: `\appid\221100\secure\1`,
Limit: 100,
})
if err != nil {
panic(err)
}
for _, server := range servers {
fmt.Printf("%s: %d/%d [%s]\n",
server.Name,
server.Players,
server.MaxPlayers,
strings.Join(server.GameType, ", "),
)
}
}
Output: Example DayZ server: 3/60 [battleye, lqs0]
func (*Client) ListAddresses ¶
ListAddresses retrieves only server addresses from GetServerList.
type CollectOptions ¶
type CollectOptions struct {
// Diagnostics receives synchronous request events when set.
Diagnostics func(DiscoveryEvent)
// MaxRequests bounds collection; zero allows all active plan queries.
MaxRequests int
}
CollectOptions controls execution of an existing discovery plan.
type DiscoveryEvent ¶
type DiscoveryEvent struct {
// Error contains a redacted request error, when one occurred.
Error string `json:"error,omitempty" yaml:"error,omitempty"`
// Filter is the expression used by the request or the checked parent branch.
Filter string `json:"filter" yaml:"filter"`
// Mismatches contains at most 32 sampled endpoints missing from a drained split side.
Mismatches []DiscoveryMismatch `json:"mismatches,omitempty" yaml:"mismatches,omitempty"`
// DurationMS is request execution and decoding time; coverage-only events use zero.
DurationMS int64 `json:"duration_ms" yaml:"duration_ms"`
// Request is the one-based number of attempted requests when the event is emitted.
Request int `json:"request" yaml:"request"`
// ReturnedRows is the response row count, or the missing-endpoint count for coverage events.
ReturnedRows int `json:"returned_rows" yaml:"returned_rows"`
// NewEndpoints is the number of previously unseen endpoints added by this response.
NewEndpoints int `json:"new_endpoints" yaml:"new_endpoints"`
// ActiveLeaves is the current executable plan-leaf count for request events.
ActiveLeaves int `json:"active_leaves" yaml:"active_leaves"`
// BufferedRecords is the current number of records retained for split validation.
BufferedRecords int `json:"buffered_records" yaml:"buffered_records"`
// Reason identifies a request or coverage condition associated with the event.
Reason DiscoveryReasons `json:"reason,omitempty" yaml:"reason,omitempty"`
}
DiscoveryEvent is an optional per-request diagnostic delivered synchronously.
type DiscoveryMismatch ¶
type DiscoveryMismatch struct {
// Address is the endpoint observed in the parent sample.
Address netip.AddrPort `json:"address" yaml:"address"`
// Key is the filter field used to partition the parent sample.
Key FilterKey `json:"key" yaml:"key"`
// Value is the candidate operand used for the partition.
Value string `json:"value" yaml:"value"`
// Matched reports which child branch the parent sample assigned this endpoint to.
Matched bool `json:"matched" yaml:"matched"`
}
DiscoveryMismatch identifies a parent-sample endpoint not recovered from the drained child branch expected to contain it.
type DiscoveryOptions ¶
type DiscoveryOptions struct {
// Diagnostics receives synchronous request and decision events when set.
Diagnostics func(DiscoveryEvent)
// Features selects filter keys the planner may use; zero uses defaults.
Features []SplitFeature
// MaxRequests bounds all requests made by one discovery run.
MaxRequests int
// MaxPlanQueries bounds the terminal queries retained for future collection.
MaxPlanQueries int
// MaxBufferedRecords bounds compact witnesses retained for branch validation.
MaxBufferedRecords int
// MaxDepth bounds the number of nested binary partitions.
MaxDepth int
// MinValueCount excludes values with insufficient sample support.
MinValueCount int
// Limit is the per-request result cap; zero uses [DefaultLimit].
Limit uint32
}
DiscoveryOptions controls bounded partition discovery.
type DiscoveryPlan ¶
type DiscoveryPlan struct {
// contains filtered or unexported fields
}
DiscoveryPlan stores the root and its binary partitions, without server data. The zero value is invalid. This unreleased format has no compatibility layer.
func (DiscoveryPlan) MarshalJSON ¶
func (plan DiscoveryPlan) MarshalJSON() ([]byte, error)
MarshalJSON serializes a valid plan using the sole supported format.
func (DiscoveryPlan) Queries ¶
func (plan DiscoveryPlan) Queries() []ListQuery
Queries returns independent queries in match-first order, or nil for an invalid plan.
func (DiscoveryPlan) QueryCount ¶
func (plan DiscoveryPlan) QueryCount() int
QueryCount returns the polling request count, or zero for an invalid plan.
func (*DiscoveryPlan) UnmarshalJSON ¶
func (plan *DiscoveryPlan) UnmarshalJSON(data []byte) error
UnmarshalJSON validates the document before replacing the receiver.
func (DiscoveryPlan) Validate ¶
func (plan DiscoveryPlan) Validate() error
Validate checks resource bounds and derives every executable partition.
type DiscoveryReasons ¶
type DiscoveryReasons uint16
DiscoveryReasons describes independent reasons discovery could not establish an operationally drained result.
const ( // DiscoveryReasonRequestBudget marks work skipped after the request budget. DiscoveryReasonRequestBudget DiscoveryReasons = 1 << iota // DiscoveryReasonPlanQueryBudget marks work blocked by the terminal-leaf cap. DiscoveryReasonPlanQueryBudget // DiscoveryReasonBufferBudget marks work skipped by the witness-memory cap. DiscoveryReasonBufferBudget // DiscoveryReasonDepthLimit marks a branch stopped at the maximum split depth. DiscoveryReasonDepthLimit // DiscoveryReasonNoUsefulSplit marks a saturated branch without a safe split. DiscoveryReasonNoUsefulSplit // DiscoveryReasonSaturated marks an active leaf that may be truncated. DiscoveryReasonSaturated // DiscoveryReasonInconsistent marks contradictory split observations. DiscoveryReasonInconsistent // DiscoveryReasonUnverifiedSemantics marks a split lacking membership evidence. DiscoveryReasonUnverifiedSemantics // DiscoveryReasonRequestFailure marks an interrupted or failed request. DiscoveryReasonRequestFailure )
func (DiscoveryReasons) Has ¶
func (reasons DiscoveryReasons) Has(reason DiscoveryReasons) bool
Has reports whether all bits in reason are present.
type DiscoveryResult ¶
type DiscoveryResult[T any] struct { // Plan stores the filters for later collection, not the observed records. Plan DiscoveryPlan `json:"plan" yaml:"plan"` // Result contains records and status from the discovery requests. Result[T] }
DiscoveryResult contains a first-run result and its reusable partition plan.
type DiscoveryStatus ¶
type DiscoveryStatus struct {
// Requests is the number of attempted HTTP requests.
Requests int `json:"requests" yaml:"requests"`
// Unresolved counts plan branches or collection queries not drained successfully.
Unresolved int `json:"unresolved" yaml:"unresolved"`
// Reasons is the combined set of conditions that prevented a clean drain.
Reasons DiscoveryReasons `json:"reasons" yaml:"reasons"`
}
DiscoveryStatus describes current operational coverage without claiming a coherent global Steam snapshot.
func (DiscoveryStatus) Complete ¶
func (status DiscoveryStatus) Complete() bool
Complete reports whether all planned partitions were operationally drained.
type Filter ¶
type Filter struct {
// contains filtered or unexported fields
}
Filter builds low-level Master Server Query Protocol filter expressions. Its zero value is ready to use. It preserves repeated conditions and their order, does not validate keys or operands, and cannot combine NOR and NAND groups. Use NewQueryFilter for structural validation and known contradictions.
func NewFilter ¶
func NewFilter() *Filter
NewFilter creates an empty filter. The zero value of Filter is also usable.
func (*Filter) RemoveNand ¶
RemoveNand removes the first matching condition from the NAND group.
type FilterKey ¶
type FilterKey string
FilterKey identifies a field in Steam's backslash-delimited master-server filter syntax. Valve's native matchmaking documentation describes this grammar, but is not an endpoint-specific contract for GetServerList. A recognized key is not a guarantee that every game implements it identically.
Filter composition follows these rules:
- Positive conditions are conjunctive: every condition must match.
- Repeated keys are preserved, not overwritten. In particular, one server may carry multiple gametype tags, so repeated gametype conditions can match the same server and do not form exclusive buckets.
- A group combines its predicates as OR, NOR, or NAND. QueryFilter supports one flat group alongside the positive conjunction; it is not a general nested-expression builder. Filter is a lower-level pair builder, not a nested-expression builder; ListQuery.Filter accepts a caller-built string.
- Different exact map predicates conflict in a positive conjunction. Use an OR group when either of several exact maps is acceptable.
Bounded live DayZ probes confirmed repeated-gametype conjunction and selected NOR complements, including tested map/gametype combinations. They do not establish universal behavior for every key, game, or filter size. In particular, boolean-like zero values are not reliable generic negations, gameaddr NOR is not a validated address complement, and no global GetServerList predicate-count limit has been established. QueryFilter checks encoding constraints and known contradictions; it cannot prove how Steam will evaluate a request. Filter intentionally leaves raw operands to callers.
const ( // KeyDedicated selects servers marked as dedicated; // "1" is the conventional flag value. KeyDedicated FilterKey = "dedicated" // KeySecure selects VAC-secure servers; // "1" is the conventional flag value. KeySecure FilterKey = "secure" // KeyGameDir selects a game directory, such as "dayz" or "cstrike". KeyGameDir FilterKey = "gamedir" // KeyMap selects servers running the specified map. KeyMap FilterKey = "map" // KeyLinux selects Linux servers; // "1" is the conventional flag value. KeyLinux FilterKey = "linux" // KeyPassword filters password protection; // GetServerList-specific value semantics are not validated here. KeyPassword FilterKey = "password" // KeyEmpty excludes empty servers with the documented value "1"; // use KeyNoPlayers to select empty servers. KeyEmpty FilterKey = "empty" // KeyFull excludes full servers with the documented value "1"; // use KeyNotFull to select servers below capacity. KeyFull FilterKey = "full" // KeyProxy filters proxy status; // GetServerList-specific value semantics are not validated here. KeyProxy FilterKey = "proxy" // KeyAppID selects servers running the specified Steam application ID. KeyAppID FilterKey = "appid" // KeyNotAppID excludes servers running the specified Steam application ID. KeyNotAppID FilterKey = "napp" // KeyNoPlayers selects servers reporting no players with the positive value "1". KeyNoPlayers FilterKey = "noplayers" // KeyNotFull selects servers below their player limit. KeyNotFull FilterKey = "notfull" // KeyWhite filters whitelist status; // GetServerList-specific value semantics are not validated here. KeyWhite FilterKey = "white" // KeyGameType selects servers with a tag from their game-type list. KeyGameType FilterKey = "gametype" // KeyGameData selects servers with the specified hidden game-data tag. KeyGameData FilterKey = "gamedata" // KeyName selects servers whose names match the supplied wildcard pattern. KeyName FilterKey = "name_match" // KeyVersion selects servers whose versions match the supplied wildcard pattern. KeyVersion FilterKey = "version_match" // KeySingleAddr collapses results to one server per IP with "1" or "0". KeySingleAddr FilterKey = "collapse_addr_hash" // KeyGameAddr selects servers at the specified IP address and optional port. KeyGameAddr FilterKey = "gameaddr" )
type GroupKind ¶
type GroupKind string
GroupKind selects how predicates in a validated filter group are combined.
type HTTPError ¶
type HTTPError struct {
// Status is the HTTP status text, when provided by the response.
Status string
// StatusCode is the numeric HTTP status code.
StatusCode int
}
HTTPError reports a non-success HTTP response from Steam or a compatible endpoint.
type HandlerOption ¶
type HandlerOption func(*handlerConfig)
HandlerOption configures the Web API-compatible HTTP handler.
func WithMaxLimit ¶
func WithMaxLimit(limit uint32) HandlerOption
WithMaxLimit bounds the limit accepted by the HTTP handler.
func WithRequiredKey ¶
func WithRequiredKey(key string) HandlerOption
WithRequiredKey enables constant-time byte comparison for equal-length keys. An empty key disables authentication.
type ListQuery ¶
type ListQuery struct {
// Filter is the raw master-server filter expression sent to the backend.
Filter string `json:"filter,omitempty" yaml:"filter,omitempty"`
// Limit is the maximum number of records requested; zero uses the package default.
Limit uint32 `json:"limit,omitempty" yaml:"limit,omitempty"`
}
ListQuery contains parameters for a rich server-list backend. A zero limit selects the default, capped by the handler's configured maximum.
type Option ¶
type Option func(*clientConfig) error
Option configures a Web API client.
func WithBaseURL ¶
WithBaseURL replaces the full GetServerList endpoint URL. It is useful for compatible local handlers and deterministic tests.
func WithHTTPClient ¶
WithHTTPClient injects the HTTP client used for requests.
func WithMaxResponseSize ¶
WithMaxResponseSize limits the response body read by the client.
type Predicate ¶
type Predicate struct {
// Key selects the filter field.
Key FilterKey `json:"key" yaml:"key"`
// Value is the exact operand encoded for the selected field.
Value string `json:"value" yaml:"value"`
}
Predicate is one key/value condition in a validated server filter.
type PredicateGroup ¶
type PredicateGroup struct {
// Kind selects OR, NOR, or NAND behavior for the flat predicate list.
Kind GroupKind `json:"kind" yaml:"kind"`
// Predicates are the alternatives or exclusions combined by Kind.
Predicates []Predicate `json:"predicates" yaml:"predicates"`
}
PredicateGroup combines its predicates using one protocol group operator.
type Provider ¶
type Provider interface {
// List returns server records matching the query.
List(ctx context.Context, query ListQuery) ([]Server, error)
}
Provider supplies rich records to the Web API-compatible handler.
type ProviderFunc ¶
ProviderFunc adapts a function to the Provider interface.
func (ProviderFunc) List ¶
List calls f with the requested query. A nil function returns ErrNilProvider.
type QueryFilter ¶
type QueryFilter struct {
// contains filtered or unexported fields
}
QueryFilter is an immutable filter expression validated for encoding shape and known contradictions.
Use NewQueryFilter to construct one; use Filter when the caller needs unrestricted raw encoding.
Validation is local: it does not contact Steam or guarantee that a key, value, or Boolean composition has the expected meaning on a particular GetServerList backend. The supported expression is a positive conjunction and at most one flat OR, NOR, or NAND group; arbitrary nesting is unsupported.
func NewQueryFilter ¶
func NewQueryFilter(all []Predicate, group *PredicateGroup) (QueryFilter, error)
NewQueryFilter validates and copies a conjunction and an optional flat Boolean group. It rejects malformed operands and only those contradictions established by exact local invariants or validated game-type complement behavior; it does not rewrite or normalize caller input.
func (QueryFilter) String ¶
func (q QueryFilter) String() string
String encodes the validated expression using Steam's backslash-delimited filter syntax.
type Result ¶
type Result[T any] struct { // Items contains the unique records retained from successful responses. Items []T `json:"items" yaml:"items"` // Status describes request and partition work that remains unresolved. Status DiscoveryStatus `json:"status" yaml:"status"` }
Result contains records from every successful query in one operation.
type Server ¶
type Server struct {
// Addr is the address and query port reported by the listing backend.
Addr netip.AddrPort `yaml:"addr" json:"addr"`
// Name is the server's advertised display name.
Name string `yaml:"name" json:"name"`
// GameDir is the server's game directory, such as "dayz" or "cstrike".
GameDir string `yaml:"gamedir" json:"gamedir"`
// Map is the map currently reported by the server.
Map string `yaml:"map" json:"map"`
// Product identifies the game product reported by the backend.
Product string `yaml:"product" json:"product"`
// Version is the game version reported by the server.
Version string `yaml:"version" json:"version"`
// OS is the operating-system marker reported by the backend.
OS string `yaml:"os" json:"os"`
// GameType contains the server's comma-separated game tags as separate values.
GameType []string `yaml:"gametype" json:"gametype"`
// SteamID is the server's Steam identifier.
SteamID uint64 `yaml:"steamid" json:"steamid,string"`
// AppID identifies the hosted Steam application.
AppID uint32 `yaml:"appid" json:"appid"`
// Region is the backend's numeric region identifier.
Region int32 `yaml:"region,omitempty" json:"region,omitempty"`
// Players is the current player count reported by the server.
Players int32 `yaml:"players" json:"players"`
// MaxPlayers is the advertised player capacity.
MaxPlayers int32 `yaml:"max_players" json:"max_players"`
// Bots is the current bot count reported by the server.
Bots int32 `yaml:"bots,omitempty" json:"bots,omitempty"`
// GamePort is the gameplay port reported separately from Addr.
GamePort uint16 `yaml:"gameport" json:"gameport"`
// SpectatorPort is the optional spectator port.
SpectatorPort uint16 `yaml:"specport,omitempty" json:"specport,omitempty"`
// Dedicated reports whether the backend marks the server as dedicated.
Dedicated bool `yaml:"dedicated" json:"dedicated"`
// Secure reports whether the server advertises secure authentication.
Secure bool `yaml:"secure" json:"secure"`
}
Server is the rich server record returned by a listing backend.
type ServerLite ¶
type ServerLite struct {
// Addr is the address and query port reported by the listing backend.
Addr netip.AddrPort `yaml:"addr" json:"addr"`
// Map is the map currently reported by the server.
Map string `yaml:"map" json:"map"`
// Version is the game version reported by the server.
Version string `yaml:"version" json:"version"`
// OS is the operating-system marker reported by the backend.
OS string `yaml:"os" json:"os"`
// GameType contains the server's comma-separated game tags as separate values.
GameType []string `yaml:"gametype" json:"gametype"`
// Players is the current player count reported by the server.
Players int32 `yaml:"players" json:"players"`
// MaxPlayers is the advertised player capacity.
MaxPlayers int32 `yaml:"max_players" json:"max_players"`
// Dedicated reports whether the backend marks the server as dedicated.
Dedicated bool `yaml:"dedicated" json:"dedicated"`
// Secure reports whether the server advertises secure authentication.
Secure bool `yaml:"secure" json:"secure"`
}
ServerLite contains the address and fields used by adaptive discovery.
type Servers ¶
type Servers []Server
Servers is a collection of server records returned by a listing backend.
func (Servers) GetVersionMap ¶
GetVersionMap counts the servers for each reported game version.
Example ¶
package main
import (
"fmt"
slist "github.com/woozymasta/steamserverlist"
)
func main() {
servers := slist.Servers{
{Version: "1.2.3"},
{Version: "1.2.3"},
{Version: "1.2.4"},
}
versions := servers.GetVersionMap()
fmt.Printf("1.2.3: %d\n", versions["1.2.3"])
fmt.Printf("1.2.4: %d\n", versions["1.2.4"])
}
Output: 1.2.3: 2 1.2.4: 1
type SplitFeature ¶
type SplitFeature struct {
// Key selects one supported field for partition candidates.
Key FilterKey `json:"key" yaml:"key"`
// Weight favors or penalizes a feature in the sampled balance score.
Weight float64 `json:"weight" yaml:"weight"`
}
SplitFeature enables a built-in filter key for candidate partitioning.
func DefaultSplitFeatures ¶
func DefaultSplitFeatures() []SplitFeature
DefaultSplitFeatures returns the package's default discovery properties.