sweb

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 11 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 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         string      `json:"plan_id"`
	PlanName       string      `json:"plan_name"`
	PlanPrice      int         `json:"plan_price"`
	CPU            int         `json:"cpu"`
	RAM            int         `json:"ram"`
	Disk           string      `json:"disk"`
	DiskGB         int         `json:"diskGb"`
	Active         int         `json:"active"`
	IsRunning      int         `json:"is_running"`
	CurrentAction  string      `json:"current_action"`
	OSDistribution string      `json:"os_distribution"`
	OSDistrID      int         `json:"os_distr_id"`
	Category       string      `json:"category"`
	MAC            string      `json:"mac"`
	IP             string      `json:"ip"`
	ExtIPs         []string    `json:"ext_ips"`
	OrderedIPCount int         `json:"ordered_ip_count"`
	Datacenter     string      `json:"datacenter"`
	DatacenterID   string      `json:"datacenter_id"`
	PasswordAccess bool        `json:"password_access"`
	SSHKeys        []SSHKeyRef `json:"ssh_keys"`
	Features       VPSFeatures `json:"features"`
	TSCreate       string      `json:"ts_create"`
}

VPS is a VPS instance as returned by List (method "index"). Field set confirmed against a real API response (Evidence phase). Some rarely used / always-null fields (local_*, isp, protected_ips, parent_plan_id) are omitted; add them when a use arises.

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 int    `json:"price_per_month"`
	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) 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.

Jump to

Keyboard shortcuts

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