Documentation
¶
Overview ¶
Package sweb is a Go client for the SpaceWeb (sweb.ru) hosting API.
The API speaks JSON-RPC 2.0 over HTTPS POST. A Client wraps the transport (envelope, auth, error handling); typed operations are grouped into services (e.g. Client.VPS) in the spirit of the kubectl/yc clients.
SpaceWeb issues short-lived session tokens and has no refresh-token flow. Use WithCredentials so the client transparently re-exchanges login+password for a fresh token when the session expires.
Index ¶
- Constants
- type AvailableConfig
- type Category
- type Client
- type CreateVPSRequest
- type Datacenter
- type Error
- type FirstOrderInfo
- type FlexFloat
- type FlexInt
- type IPAddress
- type IPAddressList
- type IPInfo
- type IPService
- func (s *IPService) Add(ctx context.Context, billingID string, number int) (json.RawMessage, error)
- func (s *IPService) AddLocal(ctx context.Context, billingID string) error
- func (s *IPService) EditPtr(ctx context.Context, ip, ptr string) error
- func (s *IPService) GetPtr(ctx context.Context, ip string) (string, error)
- func (s *IPService) Info(ctx context.Context, billingID string) (*IPInfo, error)
- func (s *IPService) Move(ctx context.Context, ip, billingID string) error
- func (s *IPService) Remove(ctx context.Context, billingID, ip string) error
- func (s *IPService) RemoveLocal(ctx context.Context, billingID string) error
- func (s *IPService) WaitForLocalIP(ctx context.Context, billingID string, interval time.Duration) (LocalIP, error)
- type IPVPSInfo
- type ISPInfo
- type LocalIP
- type LocalIPList
- type OSOption
- type OSPanel
- type Option
- type SSHKeyRef
- type VPS
- type VPSFeatures
- type VPSLogEntry
- type VPSPlan
- type VPSService
- func (s *VPSService) AvailableConfig(ctx context.Context) (*AvailableConfig, error)
- func (s *VPSService) ChangePlan(ctx context.Context, billingID string, vpsPlanID int) error
- func (s *VPSService) Copy(ctx context.Context, billingID string, vpsPlanID int) (json.RawMessage, error)
- func (s *VPSService) Create(ctx context.Context, req CreateVPSRequest) (json.RawMessage, error)
- func (s *VPSService) GetConstructorPlanID(ctx context.Context, cpuCores, ramGB, diskGB, categoryID int) (int, error)
- func (s *VPSService) GetFirstOrderInfo(ctx context.Context) (*FirstOrderInfo, error)
- func (s *VPSService) IsRunning(ctx context.Context, billingID string) (bool, error)
- func (s *VPSService) List(ctx context.Context) ([]VPS, error)
- func (s *VPSService) Logs(ctx context.Context, billingID string) ([]VPSLogEntry, error)
- func (s *VPSService) PowerOff(ctx context.Context, billingID string) error
- func (s *VPSService) PowerOn(ctx context.Context, billingID string) error
- func (s *VPSService) Reboot(ctx context.Context, billingID string) error
- func (s *VPSService) ReinstallOS(ctx context.Context, billingID string, distributiveID int, keepDisk bool) error
- func (s *VPSService) Remove(ctx context.Context, billingID string) (json.RawMessage, error)
- func (s *VPSService) Rename(ctx context.Context, billingID, alias string) error
- func (s *VPSService) WaitForIdle(ctx context.Context, billingID string, poll time.Duration, ...) (*VPS, error)
Constants ¶
const DefaultBaseURL = "https://api.sweb.ru"
DefaultBaseURL is the production SpaceWeb API root.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AvailableConfig ¶
type AvailableConfig struct {
VPSPlans []VPSPlan `json:"vpsPlans"`
SelectOS []OSOption `json:"selectOs"`
OSPanel []OSPanel `json:"osPanel"`
Datacenters []Datacenter `json:"datacenters"`
Categories []Category `json:"categories"`
}
AvailableConfig is the catalog of selectable options for creating a VPS (method "getAvailableConfig"). Shapes confirmed against a real response. selectPanel and the kit{} configurator ranges are omitted for now — add them when the CLI/provider need the custom-configurator flow.
type Client ¶
type Client struct {
// VPS groups VPS operations (endpoint /vps).
VPS *VPSService
// IP groups IP operations (endpoint /vps/ip): local network + public IPs.
IP *IPService
// contains filtered or unexported fields
}
Client talks to the SpaceWeb JSON-RPC API. Construct it with New.
func New ¶
New builds a Client. A token (WithToken) and/or credentials (WithCredentials) are optional but required for authenticated endpoints.
func (*Client) CreateToken ¶
CreateToken exchanges a login + password for a personal access token via the unauthenticated endpoint (/notAuthorized/, method getToken). The returned token is then supplied via WithToken for authenticated calls.
type CreateVPSRequest ¶
type CreateVPSRequest struct {
DistributiveID int `json:"distributiveId"`
VPSPlanID int `json:"vpsPlanId"`
Datacenter int `json:"datacenter"`
Alias string `json:"alias"`
SSHKey string `json:"sshKey"`
MonitoringPlanID int `json:"monitoringPlanId,omitempty"`
MonitoringContactID int `json:"monitoringContactId,omitempty"`
IPCount int `json:"ipCount,omitempty"`
ProtectedIPs []int `json:"protectedIps,omitempty"`
}
CreateVPSRequest holds the parameters for Create (method "create"). Use AvailableConfig to resolve the numeric IDs (plan, distributive, datacenter).
type Datacenter ¶
type Datacenter struct {
ID string `json:"id"`
Name string `json:"name"`
Location string `json:"location"`
SiteName string `json:"site_name"`
}
Datacenter is a location a VPS can be placed in.
type Error ¶
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
Error is an API-level failure: either a JSON-RPC error object returned by the API, or a synthesized error for a non-200 HTTP response (Code = status code).
NOTE: the exact JSON-RPC error shape SpaceWeb returns is not yet confirmed against a real response (Evidence phase) — Code/Message/Data are the standard JSON-RPC fields and may need adjusting once real error payloads are recorded.
type FirstOrderInfo ¶ added in v0.4.0
type FirstOrderInfo struct {
Plan string `json:"plan"`
OS string `json:"os"`
Panel string `json:"panel"`
CPUCores FlexInt `json:"cpu_cores"`
RAM FlexInt `json:"ram"` // MB
VolumeDisk string `json:"volume_disk"` // localized, e.g. "10 ГБ"
PricePerMonth FlexFloat `json:"price_per_month"`
PayPeriod FlexInt `json:"pay_period"` // months
PriceForPeriodWithStock FlexFloat `json:"price_for_period_with_stock"`
PricePerMonthWithStock FlexFloat `json:"price_per_month_with_stock"`
Promocode string `json:"promocode"` // empty when null
ClearAvailable bool `json:"clearAvailable"`
PlanIsConstructor bool `json:"plan_is_constructor"`
IPCount FlexInt `json:"ipCount"`
ProtectedIPs []FlexInt `json:"protectedIps"`
}
FirstOrderInfo describes the account's promotional first VPS order (method "getFirstOrderInfo"), used by the onboarding / clear-first-order flow.
Doc caveats reconciled against a real response: cpu_cores/ram come as quoted strings; pay_period is a month COUNT (not a price, despite the doc); and the two *_with_stock descriptions are swapped in the docs — field names + values are authoritative.
type FlexFloat ¶ added in v0.3.0
type FlexFloat float64
FlexFloat is FlexInt's fractional sibling for money fields: decodes from a JSON number (0.9), a quoted string ("0.9"), or null (→ 0). Marshals back as a bare JSON number.
func (FlexFloat) MarshalJSON ¶ added in v0.3.0
MarshalJSON emits a bare JSON number (shortest round-trippable form).
func (*FlexFloat) UnmarshalJSON ¶ added in v0.3.0
UnmarshalJSON accepts 0.9, "0.9", "" and null.
type FlexInt ¶ added in v0.3.0
type FlexInt int64
FlexInt is an int64 that decodes from EITHER a JSON number (4) or a quoted string ("4"), and from null (→ 0). The SpaceWeb API returns many numeric fields inconsistently as one or the other across nodes/plans, so a plain int crashes on the string form (the plan_price/ram class of bug). Marshals back as a bare JSON number.
func (FlexInt) MarshalJSON ¶ added in v0.3.0
MarshalJSON emits a bare JSON number.
func (*FlexInt) UnmarshalJSON ¶ added in v0.3.0
UnmarshalJSON accepts 4, "4", "" and null.
type IPAddress ¶ added in v0.8.0
type IPAddress struct {
IP string `json:"ip"`
Gateway string `json:"gateway"`
Netmask string `json:"netmask"`
Datacenter FlexInt `json:"datacenter"`
PTR string `json:"ptr"`
Price FlexFloat `json:"price"` // money: the API returns fractional prices (e.g. 142.06)
}
IPAddress is a public IP bound to (or orderable for) a VPS.
type IPAddressList ¶ added in v0.8.2
type IPAddressList []IPAddress
IPAddressList is []IPAddress with the same array-or-object tolerance.
func (*IPAddressList) UnmarshalJSON ¶ added in v0.8.2
func (l *IPAddressList) UnmarshalJSON(b []byte) error
UnmarshalJSON accepts an array, a single object, or null.
type IPInfo ¶ added in v0.8.0
type IPInfo struct {
IPs IPAddressList `json:"ips"`
ProtectedIPs json.RawMessage `json:"protected_ips"` // raw: shape varies; decode on demand
LocalIP LocalIPList `json:"local_ip"`
VPS IPVPSInfo `json:"vps"`
}
IPInfo is the per-VPS IP inventory returned by the "index" method: public IPs, protected IPs, and the local-network attachment (if any).
type IPService ¶ added in v0.8.0
type IPService struct {
// contains filtered or unexported fields
}
IPService groups IP operations (endpoint /vps/ip): the account private (local) network and public/additional IP management.
func (*IPService) Add ¶ added in v0.11.0
Add orders number additional public IPs for a VPS (method "add"). This BILLS. Like Create, the result shape is left raw pending a recorded response — read the assigned addresses back via Info once they settle.
func (*IPService) AddLocal ¶ added in v0.8.0
AddLocal attaches the VPS to the account private (local) network. The local IP is assigned by SpaceWeb — read it back via Info or WaitForLocalIP. This is the declarative way to put an EXISTING VPS on the private network (no re-create).
func (*IPService) EditPtr ¶ added in v0.11.0
EditPtr sets the PTR (reverse-DNS) record for an IP (method "editPtr"). An empty ptr resets it to the provider default. Action 1/0 result.
func (*IPService) GetPtr ¶ added in v0.11.0
GetPtr returns the PTR (reverse-DNS) record for an IP (method "getPtr"). Read-only. Tolerates the record arriving as a bare string or a {"ptr": …} object.
func (*IPService) Info ¶ added in v0.8.0
Info returns the IP inventory for a VPS (method "index"). Read-only.
func (*IPService) Move ¶ added in v0.11.0
Move attaches an IP to a VPS, or detaches it when billingID is empty (method "move"; the API takes billingId=null to detach). Action 1/0 result.
func (*IPService) Remove ¶ added in v0.11.0
Remove releases a public IP from a VPS (method "remove"). Action 1/0 result.
func (*IPService) RemoveLocal ¶ added in v0.8.0
RemoveLocal detaches the VPS from the private (local) network.
func (*IPService) WaitForLocalIP ¶ added in v0.8.0
func (s *IPService) WaitForLocalIP(ctx context.Context, billingID string, interval time.Duration) (LocalIP, error)
WaitForLocalIP polls Info until the VPS reports a local IP (attachment can be asynchronous), returning the first one, or until ctx is done.
type IPVPSInfo ¶ added in v0.8.0
type IPVPSInfo struct {
BillingID string `json:"billingId"`
CurrentAction string `json:"currentAction"` // string|null
IsEmpty string `json:"isEmpty"` // "0" once the OS is installed
OrderedIPCount FlexInt `json:"ordered_ip_count"`
}
IPVPSInfo is the VPS summary embedded in the IP index.
type ISPInfo ¶ added in v0.3.0
type ISPInfo struct {
LicenseType string `json:"license_type"`
IP string `json:"ip"`
ActiveUntil string `json:"active_until"`
Price FlexFloat `json:"price"`
Link string `json:"link"`
IsBlocked FlexInt `json:"is_blocked"`
CreationTime string `json:"creation_time"`
}
ISPInfo is control-panel (ISP license) info attached to a VPS ("isp" in the index response).
type LocalIP ¶ added in v0.8.0
LocalIP is a VPS's attachment to the account private (local) network.
type LocalIPList ¶ added in v0.8.2
type LocalIPList []LocalIP
LocalIPList is []LocalIP that also decodes a bare object or null (SpaceWeb returns local_ip as [] when unattached, a single object when attached).
func (*LocalIPList) UnmarshalJSON ¶ added in v0.8.2
func (l *LocalIPList) UnmarshalJSON(b []byte) error
UnmarshalJSON accepts an array, a single object, or null.
type OSOption ¶
type OSOption struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
OSDistributionID string `json:"os_distribution_id"`
PlanID string `json:"plan_id"`
}
OSOption is a selectable OS image.
type OSPanel ¶
type OSPanel struct {
Distributive string `json:"distributive"`
OS string `json:"os"`
Panel string `json:"panel"`
AvailablePlanIDs []int `json:"availablePlanIds"`
MinRAM int `json:"minRam"`
MinStorage int `json:"minStorage"`
}
OSPanel maps a distributive/OS to the plans and minimum resources it needs.
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithBaseURL ¶
WithBaseURL overrides the API root (useful for tests / staging).
func WithCredentials ¶ added in v0.1.3
WithCredentials enables transparent token refresh: when a call fails because the session token expired, the client exchanges login+password for a fresh token (getToken) and retries once. Pair with WithOnTokenRefresh to persist it.
func WithHTTPClient ¶
WithHTTPClient injects a custom *http.Client (timeouts, transport, test server).
func WithOnTokenRefresh ¶ added in v0.1.3
WithOnTokenRefresh registers a callback invoked with the new token whenever the client refreshes it — e.g. to cache it in an OS keyring.
type VPS ¶
type VPS struct {
BillingID string `json:"billingId"`
Name string `json:"name"` // user-facing alias
UID string `json:"uid"` // stable unique id
PlanID FlexInt `json:"plan_id"`
PlanName string `json:"plan_name"`
ParentPlanID FlexInt `json:"parent_plan_id"` // nullable
PlanPrice FlexFloat `json:"plan_price"` // money, may be fractional
CPU FlexInt `json:"cpu"`
RAM FlexInt `json:"ram"` // MB; API may quote it ("1024")
Disk string `json:"disk"` // localized human size, e.g. "10 ГБ"
BlockUI FlexInt `json:"blockUi"`
Active FlexInt `json:"active"`
OSDistribution string `json:"os_distribution"`
OSDistrID FlexInt `json:"os_distr_id"`
Category string `json:"category"`
TSCreate string `json:"ts_create"`
MAC string `json:"mac"`
IP string `json:"ip"`
LocalIP string `json:"local_ip"` // nullable
LocalMAC string `json:"local_mac"` // nullable
LocalMask string `json:"local_mask"`
CurrentAction string `json:"current_action"`
IsRunning FlexInt `json:"is_running"`
ISP []ISPInfo `json:"isp"`
ExtIPs []json.RawMessage `json:"ext_ips"` // TODO: type once a populated example exists (doc: array of IP objects)
IsTest FlexInt `json:"is_test"`
IsNew bool `json:"is_new"`
Datacenter string `json:"datacenter"`
OrderedIPCount FlexInt `json:"ordered_ip_count"`
ProtectedIPs []string `json:"protected_ips"`
// Not part of the documented index response — present in an earlier recorded
// response and still consumed by the Terraform provider's computed mapping
// (disk size, datacenter id). Kept until the provider reconcile (variant B);
// index does not populate these, so they decode to zero here.
DiskGB int `json:"diskGb"`
DatacenterID string `json:"datacenter_id"`
PasswordAccess bool `json:"password_access"`
SSHKeys []SSHKeyRef `json:"ssh_keys"`
Features VPSFeatures `json:"features"`
}
VPS is a VPS instance as returned by List (method "index").
Types are reconciled against a real API response: SpaceWeb returns many numeric fields either as numbers or quoted strings (FlexInt/FlexFloat handle both), and nullable fields (parent_plan_id, local_*) as JSON null.
type VPSFeatures ¶
type VPSFeatures struct {
AllowBackups bool `json:"allowBackups"`
AllowLocalNetwork bool `json:"allowLocalNetwork"`
AllowCustomImage bool `json:"allowCustomImage"`
AllowDdosProtection bool `json:"allowDdosProtection"`
MaxIPCount int `json:"maxIpCount"`
AllowConfigurator bool `json:"allowConfigurator"`
AllowAccess bool `json:"allowAccess"`
AllowDiskConnection bool `json:"allowDiskConnection"`
AllowAutoBackups bool `json:"allowAutoBackups"`
AllowClone bool `json:"allowClone"`
}
VPSFeatures are capability flags for a VPS / plan.
type VPSLogEntry ¶ added in v0.10.0
type VPSLogEntry struct {
Type string `json:"type"`
Status string `json:"status"`
StartedAt string `json:"started_at"`
EndedAt string `json:"ended_at"`
}
VPSLogEntry is one entry of a VPS's operation log (method "logs"). Field names follow the documented shape (type/status/started_at/ended_at); the call is read-only, so the struct is reconciled from the docs pending a recorded response — unknown fields simply decode to zero.
type VPSPlan ¶
type VPSPlan struct {
ID int `json:"id"`
Name string `json:"name"`
PricePerMonth float64 `json:"price_per_month"` // money: API returns fractional prices
Category string `json:"category"`
CPUCores string `json:"cpu_cores"`
RAM string `json:"ram"`
DiskType string `json:"disk_type"`
VolumeDisk string `json:"volume_disk"`
Datacenters []int `json:"datacenters"`
SoldOut bool `json:"sold_out"`
}
VPSPlan is a purchasable VPS plan. Note SpaceWeb returns several numeric-ish fields (cpu_cores, ram, volume_disk) as strings.
type VPSService ¶
type VPSService struct {
// contains filtered or unexported fields
}
VPSService groups VPS operations. All calls hit the /vps endpoint with a JSON-RPC method.
func (*VPSService) AvailableConfig ¶
func (s *VPSService) AvailableConfig(ctx context.Context) (*AvailableConfig, error)
AvailableConfig returns the catalog of selectable VPS options (method "getAvailableConfig"): plans, OS images, datacenters, categories.
func (*VPSService) ChangePlan ¶ added in v0.5.0
ChangePlan changes a VPS's tariff plan in place (method "changePlan") — a resize without reprovisioning. billingID is the service id ("login_vps_N"); vpsPlanID is a plan id (from AvailableConfig, or GetConstructorPlanID for a custom configuration). The API returns 1 on success, 0 on failure (surfaced here as an error).
NOTE: the parameter is "planId" (per the docs' parameter table). The docs' EXAMPLE instead shows "vpsPlanId" (as in Create), but the API rejects that with -32602 "Invalid method parameter(s)" — confirmed live. NOTE: the resize is asynchronous — poll List / current_action until it settles.
func (*VPSService) Copy ¶ added in v0.10.0
func (s *VPSService) Copy(ctx context.Context, billingID string, vpsPlanID int) (json.RawMessage, error)
Copy clones a VPS into a new one on the given plan (method "copy"). billingID is the source; vpsPlanID is the new VPS's plan (from AvailableConfig, or GetConstructorPlanID for a custom configuration). Like Create, this provisions a NEW, billed VPS and runs asynchronously — the result shape is left raw pending a recorded response; find the new node via List once it settles.
func (*VPSService) Create ¶
func (s *VPSService) Create(ctx context.Context, req CreateVPSRequest) (json.RawMessage, error)
Create provisions a new VPS (method "create").
The result shape is intentionally left raw: "create" mutates (and bills), so it was not exercised during the Evidence phase. Type it once a real create response is recorded.
func (*VPSService) GetConstructorPlanID ¶ added in v0.1.4
func (s *VPSService) GetConstructorPlanID(ctx context.Context, cpuCores, ramGB, diskGB, categoryID int) (int, error)
GetConstructorPlanID resolves a custom ("configurator") plan ID for the given resources via the "getConstructorPlanId" method. ram and disk are in GB; categoryID is a catalog category id (see AvailableConfig.Categories). This is read-only — it neither creates nor bills; feed the result to Create as the VPSPlanID.
func (*VPSService) GetFirstOrderInfo ¶ added in v0.4.0
func (s *VPSService) GetFirstOrderInfo(ctx context.Context) (*FirstOrderInfo, error)
GetFirstOrderInfo returns the account's first-order info (method "getFirstOrderInfo"), or nil if there is no first order.
The API double-wraps the payload: the outer result is a one-element array whose element is itself a JSON-RPC envelope, so the object lives at result[0].result. This unwraps it.
func (*VPSService) IsRunning ¶ added in v0.9.0
IsRunning reports whether the VPS is powered on (method "isRunning"). Read-only. Note List already carries VPS.IsRunning for every node; this is the cheaper single-VPS query when only the power state is needed.
func (*VPSService) List ¶
func (s *VPSService) List(ctx context.Context) ([]VPS, error)
List returns all VPS instances (method "index").
func (*VPSService) Logs ¶ added in v0.10.0
func (s *VPSService) Logs(ctx context.Context, billingID string) ([]VPSLogEntry, error)
Logs returns the VPS's operation log (method "logs") — the record of lifecycle actions (create, reinstall, resize, …) run against the node. Read-only.
func (*VPSService) PowerOff ¶ added in v0.9.0
func (s *VPSService) PowerOff(ctx context.Context, billingID string) error
PowerOff shuts a running VPS down (method "powerOff"). Asynchronous — see PowerOn.
func (*VPSService) PowerOn ¶ added in v0.9.0
func (s *VPSService) PowerOn(ctx context.Context, billingID string) error
PowerOn boots a stopped VPS (method "powerOn"). The power change is asynchronous: the API accepts the request (returns 1) and the machine settles over the following seconds — poll IsRunning, or WaitForIdle for the current_action to clear. A JSON-RPC error (or a 0 result) surfaces as an error.
func (*VPSService) Reboot ¶ added in v0.9.0
func (s *VPSService) Reboot(ctx context.Context, billingID string) error
Reboot restarts a VPS (method "reboot"). Asynchronous — see PowerOn.
func (*VPSService) ReinstallOS ¶ added in v0.10.0
func (s *VPSService) ReinstallOS(ctx context.Context, billingID string, distributiveID int, keepDisk bool) error
ReinstallOS reinstalls the VPS's operating system (method "reinstallOs") to the given distributive (see AvailableConfig.SelectOS for the ids). This is DESTRUCTIVE — it wipes the system disk unless keepDisk is set (the API's save_disk flag). It runs asynchronously; poll WaitForIdle to await the rebuild. The API answers 1 on acceptance (0 = failure).
func (*VPSService) Remove ¶ added in v0.1.2
func (s *VPSService) Remove(ctx context.Context, billingID string) (json.RawMessage, error)
Remove deletes a VPS (method "remove"). billingID is the service identifier (format "login_vps_N"), as returned in VPS.BillingID by List.
This is destructive — it cancels the VPS. The result shape is left raw pending a recorded response.
func (*VPSService) Rename ¶ added in v0.2.0
func (s *VPSService) Rename(ctx context.Context, billingID, alias string) error
Rename changes a VPS's user-facing name/alias (method "rename"). billingID is the service identifier ("login_vps_N"); alias is the new name. This is an in-place label change — it does not reprovision or bill. The API returns 1 on success; a JSON-RPC error surfaces as *Error.
func (*VPSService) WaitForIdle ¶ added in v0.7.0
func (s *VPSService) WaitForIdle(ctx context.Context, billingID string, poll time.Duration, onPhase func(action string)) (*VPS, error)
WaitForIdle polls the VPS until its current_action is empty. SpaceWeb runs a resize / provisioning as a SEQUENCE of async actions (e.g. Modify → ExtIpAdd — an IP re-issue runs even when no extra IP was ordered), and is_running stays 1 throughout — so "settled" means current_action is idle, NOT is_running == 1.
poll is the interval between checks (default 10s). onPhase, if non-nil, is called each poll with the current action (trimmed; "" once idle) — a CLI can render it as progress. Honors ctx for cancellation / timeout; wrap ctx with a deadline to bound the wait.