Documentation
¶
Overview ¶
Package backend is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package backend composes online service handlers and compiled game RPCs in one embeddable HTTP handler.
Index ¶
- Constants
- type AfterHook
- type Backend
- func (b *Backend) AddAfterHook(fn AfterHook) error
- func (b *Backend) AddBeforeHook(fn BeforeHook) error
- func (b *Backend) Mount(prefix string, h http.Handler) error
- func (b *Backend) MountRealtime(h http.Handler) error
- func (b *Backend) MountSocial(h http.Handler) error
- func (b *Backend) RPC(name string, fn RPCFunc) error
- func (b *Backend) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type BeforeHook
- type Caller
- type Options
- type RPCFunc
- type RateLimit
- type StatusError
Examples ¶
Constants ¶
const DefaultMaxRateLimitBuckets = 10_000
DefaultMaxRateLimitBuckets is the default cap on distinct client addresses tracked in memory by each rate limiter when Options.MaxRateLimitBuckets is zero.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AfterHook ¶
AfterHook runs after a game RPC returns a result and before that result is encoded. It cannot change the response or reject the call.
type Backend ¶
type Backend struct {
// contains filtered or unexported fields
}
Backend is an embeddable service mux. Hooks and service-specific auth remain owned by the mounted handlers, while RPC authorization is supplied by the auth function given to New or NewWithOptions. Register mounts and RPCs before serving; registration is not safe to run concurrently with itself or with ServeHTTP.
Example ¶
A Backend serves mounted service handlers and authenticated game RPCs from one handler.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/nsgo-dev/game/pkg/online/backend"
)
func main() {
b := backend.New(func(r *http.Request) (backend.Caller, error) {
if r.Header.Get("Authorization") != "Bearer ana-token" {
return backend.Caller{}, errors.New("bad token")
}
return backend.Caller{AccountID: "ana"}, nil
})
_ = b.Mount("/status", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok at", r.URL.Path)
}))
_ = b.RPC("add", func(_ context.Context, c backend.Caller, raw json.RawMessage) (any, error) {
var in struct{ A, B int }
if err := json.Unmarshal(raw, &in); err != nil {
return nil, backend.StatusError{Code: http.StatusBadRequest, Err: errors.New("want two numbers")}
}
return map[string]any{"account": c.AccountID, "sum": in.A + in.B}, nil
})
call := func(method, target, body, token string) {
req := httptest.NewRequest(method, target, strings.NewReader(body))
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
b.ServeHTTP(rec, req)
fmt.Println(rec.Code, strings.TrimSpace(rec.Body.String()))
}
call("GET", "/status/health", "", "")
call("POST", "/v1/rpc/add", `{"A":2,"B":3}`, "ana-token")
call("POST", "/v1/rpc/add", `[1,2]`, "ana-token")
call("POST", "/v1/rpc/add", `{"A":2,"B":3}`, "")
}
Output: 200 ok at /health 200 {"account":"ana","sum":5} 400 want two numbers 401 unauthorized
func New ¶
New returns an empty backend with no allowed browser origins and no rate limiting. Auth is required for RPC calls and may inspect the request's bearer token using the application's verifier. Use NewWithOptions to configure CORS for RPCs or per-client rate limiting.
func NewWithOptions ¶
NewWithOptions returns an empty backend configured with opts. It validates opts.AllowedOrigins, rate limits, guest paths, bucket cap, and trusted proxies, returning an error if any setting is invalid.
func (*Backend) AddAfterHook ¶
AddAfterHook registers a hook for every successful RPC. Hooks run in registration order after the RPC returns and before its result is encoded. Register hooks before serving; registration is not safe to run concurrently with ServeHTTP.
func (*Backend) AddBeforeHook ¶
func (b *Backend) AddBeforeHook(fn BeforeHook) error
AddBeforeHook registers a hook for every RPC. Hooks run in registration order. Register hooks before serving; registration is not safe to run concurrently with ServeHTTP.
func (*Backend) Mount ¶
Mount mounts an existing service handler below prefix, such as /accounts/. The handler sees request paths with the prefix removed. A prefix without a trailing slash gets one; a prefix of "/", one that is not a clean path, one under /v1/rpc/, or one with characters other than letters, digits, '-', '_', '.' and '/' is refused, as is a prefix mounted twice.
func (*Backend) MountRealtime ¶
MountRealtime wires a realtime service handler (such as realtime.Service.Handler) directly onto the combined server's /v1/socket and /v1/notifications routes without stripping a prefix. Register it before serving; calling it with a nil handler, calling it twice, or colliding with an existing mount returns an error.
func (*Backend) MountSocial ¶
MountSocial mounts a social service HTTP handler (such as social.Service.Handler) directly at /v1/friends, /v1/friends/, /v1/groups and /v1/groups/ without stripping the prefixes. It returns an error when h is nil or either prefix has already been mounted.
func (*Backend) RPC ¶
RPC registers POST /v1/rpc/name. Name is made of letters, digits, '-', '_' and '.', is not "." or "..", and each name is registered once.
The handler's result is encoded as JSON. A StatusError with a 4xx or 5xx code is answered with that code and its message; any other error is answered with 500 and a generic message, so internal error text never reaches the client.
type BeforeHook ¶
type BeforeHook func(context.Context, Caller, string, json.RawMessage) (json.RawMessage, error)
BeforeHook runs after RPC authentication and JSON decoding, before the game RPC. It returns a replacement JSON value, nil to keep the body unchanged, or an error. A StatusError exposes a safe 4xx or 5xx response to the caller; a replacement that is not valid JSON is answered with 500, as any other error is.
type Caller ¶
type Caller struct{ AccountID string }
Caller identifies the authenticated account invoking an RPC.
type Options ¶
type Options struct {
// AllowedOrigins lists the web origins (such as "https://play.example.com")
// allowed to call composed RPC routes from a browser. Entries are validated
// with the same rules as the self-hosted online services: http or https
// scheme, non-empty host, no path, query, fragment, userinfo, wildcard or
// duplicate. When empty, cross-origin RPC preflight requests are refused
// with 403 and no Access-Control-Allow-Origin header is sent.
AllowedOrigins []string
// RateLimit sets an optional per-client-address rate limit applied to every
// non-preflight request handled by the backend (both mounted services and
// RPCs). When zero, general rate limiting is disabled.
RateLimit RateLimit
// GuestCreateRateLimit sets an optional, separate per-client-address rate
// limit for guest account creation routes (POST .../v1/guest on any mounted
// accounts service, or the paths listed in GuestCreatePaths). When set, it
// is enforced independently of RateLimit so guest-creation bursts can be
// capped tightly without starving normal RPCs or mounted routes. When zero,
// guest creation uses RateLimit if configured.
GuestCreateRateLimit RateLimit
// GuestCreatePaths optionally overrides the exact POST request paths (such
// as "/accounts/v1/guest") subject to GuestCreateRateLimit. Each entry must
// be a clean path starting with "/". When empty, POST requests whose cleaned
// path is "/v1/guest" or ends with "/v1/guest" are matched.
GuestCreatePaths []string
// TrustedProxies lists reverse-proxy IP addresses or CIDR ranges (such as
// "127.0.0.1" or "10.0.0.0/8") whose X-Forwarded-For header is trusted when
// determining the client address for rate limiting. When empty,
// X-Forwarded-For is ignored and r.RemoteAddr is always used.
TrustedProxies []string
// MaxRateLimitBuckets caps the number of distinct client-address buckets
// tracked in memory per limiter so floods from random addresses cannot grow
// memory without bound. Zero uses DefaultMaxRateLimitBuckets.
MaxRateLimitBuckets int
// Now returns the current time for rate-limit windows. Nil uses time.Now.
Now func() time.Time
}
Options configures CORS and per-client rate limiting on a Backend.
type RateLimit ¶
type RateLimit struct {
// Limit is the maximum burst of requests allowed per client address within Window.
Limit int
// Window is the rolling duration over which Limit refills.
Window time.Duration
}
RateLimit limits how many requests one client address may make within Window. Both Limit and Window must be positive when configured; the zero value leaves the limit disabled.
type StatusError ¶
StatusError lets a game RPC choose its HTTP error status. Its message is sent to the client, so it must be safe to show.
func (StatusError) Error ¶
func (e StatusError) Error() string
Error returns the wrapped error's message, or the status text when Err is nil.