sweb

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2026 License: MIT Imports: 12 Imported by: 0

README

sweb-go-sdk

CI Go Reference Go Report Card

A Go client for the SpaceWeb (sweb.ru) hosting API.

The API speaks JSON-RPC 2.0 over HTTPS. This SDK wraps the transport (envelope, Bearer auth, error handling) and exposes typed operations grouped into services. It is the shared foundation for the sweb CLI and a future Terraform provider.

Install

go get github.com/sanchpet/sweb-go-sdk

Usage

package main

import (
	"context"
	"fmt"

	sweb "github.com/sanchpet/sweb-go-sdk"
)

func main() {
	ctx := context.Background()

	// 1. Exchange credentials for a token (unauthenticated endpoint).
	tmp := sweb.New()
	token, err := tmp.CreateToken(ctx, "login", "password")
	if err != nil {
		panic(err)
	}

	// 2. Use the token for authenticated calls.
	c := sweb.New(sweb.WithToken(token))

	vpsList, err := c.VPS.List(ctx)
	if err != nil {
		panic(err)
	}
	fmt.Println(vpsList)
}

Status

Early. The transport (JSON-RPC envelope, auth, error handling) is covered by tests. Resource result types (VPS list, available config, create) are provisional and will be firmed up against recorded API responses.

License

MIT — see LICENSE.

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

View Source
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 Category

type Category struct {
	ID   string `json:"id"`
	Slug string `json:"slug"`
	Name string `json:"name"`
}

Category groups plans.

type Client

type Client struct {

	// VPS groups VPS operations (endpoint /vps).
	VPS *VPSService
	// contains filtered or unexported fields
}

Client talks to the SpaceWeb JSON-RPC API. Construct it with New.

func New

func New(opts ...Option) *Client

New builds a Client. A token (WithToken) and/or credentials (WithCredentials) are optional but required for authenticated endpoints.

func (*Client) CreateToken

func (c *Client) CreateToken(ctx context.Context, login, password string) (string, error)

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.

func (*Client) Token added in v0.1.3

func (c *Client) Token() string

Token returns the current Bearer token (which may have been refreshed).

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.

func (*Error) Error

func (e *Error) Error() string

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

func (f FlexFloat) MarshalJSON() ([]byte, error)

MarshalJSON emits a bare JSON number (shortest round-trippable form).

func (*FlexFloat) UnmarshalJSON added in v0.3.0

func (f *FlexFloat) UnmarshalJSON(b []byte) error

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

func (f FlexInt) MarshalJSON() ([]byte, error)

MarshalJSON emits a bare JSON number.

func (*FlexInt) UnmarshalJSON added in v0.3.0

func (f *FlexInt) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts 4, "4", "" and null.

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 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

func WithBaseURL(u string) Option

WithBaseURL overrides the API root (useful for tests / staging).

func WithCredentials added in v0.1.3

func WithCredentials(login, password string) Option

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

func WithHTTPClient(h *http.Client) Option

WithHTTPClient injects a custom *http.Client (timeouts, transport, test server).

func WithOnTokenRefresh added in v0.1.3

func WithOnTokenRefresh(fn func(string)) Option

WithOnTokenRefresh registers a callback invoked with the new token whenever the client refreshes it — e.g. to cache it in an OS keyring.

func WithToken

func WithToken(t string) Option

WithToken sets the Bearer token used for authenticated endpoints.

type SSHKeyRef

type SSHKeyRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

SSHKeyRef is an SSH key attached to a VPS.

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 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) Create

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) List

func (s *VPSService) List(ctx context.Context) ([]VPS, error)

List returns all VPS instances (method "index").

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.

Jump to

Keyboard shortcuts

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