gotsw

package module
v2.0.6 Latest Latest
Warning

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

Go to latest
Published: May 29, 2025 License: MIT Imports: 15 Imported by: 0

README

GoTSW

The official Teraswitch Go client.

Install

go get github.com/teraswitch/gotsw/v2

Usage

import "github.com/teraswitch/gotsw/v2"
Authentication
package main

import (
    "github.com/teraswitch/gotsw/v2"
)

func main() {
    client := gotsw.New("id:secret")
}

For more examples, see the examples directory.

Documentation

Index

Constants

View Source
const (
	// SessionTokenHeader is the header to use for authentication.
	SessionTokenHeader = "Authorization"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	HTTPClient *http.Client
	URL        *url.URL

	// SessionTokenHeader is an optional custom header to use for setting tokens. By
	// default 'Coder-Session-Token' is used.
	SessionTokenHeader string

	// PlainLogger may be set to log HTTP traffic in a human-readable form.
	// It uses the LogBodies option.
	PlainLogger io.Writer
	// contains filtered or unexported fields
}

Client is an HTTP caller for methods to the Coder API. @typescript-ignore Client

func New

func New(auth string) *Client

New creates a Coder client for the provided URL.

func (*Client) Authorization

func (c *Client) Authorization() string

SessionToken returns the currently set token for the client.

func (*Client) CreateMetalService

func (c *Client) CreateMetalService(ctx context.Context, projectID int64, req *CreateBareMetalRequest) (*MetalResponse, error)

CreateMetalService creates a new metal service

func (*Client) CreateSshKey added in v2.0.2

func (c *Client) CreateSshKey(ctx context.Context, projectID int64, key CreateSshKeyRequest) (SSHKey, error)

CreateSshKey creates a new SSH key

func (*Client) GetMetalAvailability

func (c *Client) GetMetalAvailability(ctx context.Context, projectId int64, regionId string) (*MetalConfigurationResponse, error)

Update the GetMetalAvailability function to use the new response type

func (*Client) GetMetalLogs

func (c *Client) GetMetalLogs(ctx context.Context, id int64) (*LogMessageResponse, error)

GetMetalLogs retrieves logs for a metal service

func (*Client) GetMetalService

func (c *Client) GetMetalService(ctx context.Context, id int64) (*MetalResponse, error)

GetMetalService retrieves a single metal service by ID

func (*Client) GetSshKey added in v2.0.2

func (c *Client) GetSshKey(ctx context.Context, id int64) (SSHKey, error)

GetSshKey retrieves a specific SSH key by ID

func (*Client) ListMetal

func (c *Client) ListMetal(ctx context.Context, opts ListMetalOptions) (*ListMetalResponse, error)

ListMetal retrieves a list of metal services with optional filtering

func (*Client) ListMetalTiers

func (c *Client) ListMetalTiers(ctx context.Context, tierType MetalTierType) (*MetalTierResponse, error)

ListMetalTiers retrieves all metal service tiers with optional type filter

func (*Client) ListSshKeys added in v2.0.2

func (c *Client) ListSshKeys(ctx context.Context) ([]SSHKey, error)

ListSshKeys retrieves all SSH keys assigned to your project

func (*Client) LogBodies

func (c *Client) LogBodies() bool

LogBodies returns whether requests and response bodies are logged.

func (*Client) Logger

func (c *Client) Logger() *slog.Logger

Logger returns the logger for the client.

func (*Client) ReinstallMetalService added in v2.0.1

func (c *Client) ReinstallMetalService(ctx context.Context, id int64, req *ReinstallMetalRequest) (*MetalResponse, error)

ReinstallMetalService reinstalls a metal service by ID

func (*Client) RenameMetalService

func (c *Client) RenameMetalService(ctx context.Context, id int64, name string) (*Result[struct{}], error)

RenameMetalService renames a metal service

func (*Client) Request

func (c *Client) Request(ctx context.Context, method, path string, body interface{}, opts ...RequestOption) (*http.Response, error)

Request performs a HTTP request with the body provided. The caller is responsible for closing the response body.

func (*Client) SendPowerCommand

func (c *Client) SendPowerCommand(ctx context.Context, id int64, command PowerCommand) (*MetalResponse, error)

SendPowerCommand sends a power command to a metal service

func (*Client) SetAuthorization

func (c *Client) SetAuthorization(token string) *Client

SetSessionToken returns the currently set token for the client.

func (*Client) SetClient added in v2.0.1

func (c *Client) SetClient(client *http.Client) *Client

func (*Client) SetLogBodies

func (c *Client) SetLogBodies(logBodies bool) *Client

SetLogBodies sets whether to log request and response bodies.

func (*Client) SetLogger

func (c *Client) SetLogger(logger *slog.Logger) *Client

SetLogger sets the logger for the client.

func (*Client) SetPlainLogger

func (c *Client) SetPlainLogger(plainLogger io.Writer) *Client

SetPlainLogger may be set to log HTTP traffic in a human-readable form. It uses the LogBodies option.

type CpuDetails added in v2.0.6

type CpuDetails struct {
	ID             string `json:"id"`             // ID of the CPU
	CPU            string `json:"cpu"`            // The CPU model for the tier
	CPUDescription string `json:"cpuDescription"` // Description of CPU (cores/threads)
}

CpuDetails represents the CPU details for a metal tier

type CreateBareMetalRequest

type CreateBareMetalRequest struct {
	Quantity       int               `json:"quantity,omitempty"`
	DisplayName    string            `json:"displayName"`
	RegionID       string            `json:"regionId"`
	TierID         string            `json:"tierId"`
	MemoryGB       int               `json:"memoryGb"`
	ImageID        string            `json:"imageId"`
	Tags           []string          `json:"tags"`
	TemplateID     *int              `json:"templateId,omitempty"`
	SSHKeyIDs      []int             `json:"sshKeyIds"`
	Disks          map[string]string `json:"disks"`
	IPXEUrl        *string           `json:"ipxeUrl"`
	UserData       *string           `json:"userData"`
	Password       *string           `json:"password,omitempty"`
	ReservePricing bool              `json:"reservePricing"`
	Partitions     []Partition       `json:"partitions,omitempty"`
	RaidArrays     []RaidArray       `json:"raidArrays,omitempty"`
}

CreateBareMetalRequest represents the request parameters for creating a new metal service

type CreateSshKeyRequest added in v2.0.2

type CreateSshKeyRequest struct {
	DisplayName string `json:"displayName"`
	ProjectID   int64  `json:"projectId"`
	Key         string `json:"key"`
}

type DriveDetails

type DriveDetails struct {
	DeviceName string `json:"deviceName,omitempty"`
	Serial     string `json:"serial,omitempty"`
}

DriveDetails contains additional information about a drive

type DriveSlot

type DriveSlot struct {
	ID       string               `json:"id"`       // ID in format like nvme0n1
	Default  string               `json:"default"`  // Default value for this drive slot
	Required bool                 `json:"required"` // Whether a drive is required in this slot
	Options  []MetalStorageDevice `json:"options"`  // Available drives for this slot
}

DriveSlot represents a slot for a storage drive

type EventState

type EventState string

EventState represents the state of a provisioning event

const (
	EventStatePending    EventState = "Pending"
	EventStateInProgress EventState = "InProgress"
	EventStateComplete   EventState = "Complete"
	EventStateError      EventState = "Error"
)

type FileSystem

type FileSystem string
const (
	FileSystemBtrfs       FileSystem = "Btrfs"
	FileSystemExt2        FileSystem = "Ext2"
	FileSystemExt4        FileSystem = "Ext4"
	FileSystemFat32       FileSystem = "Fat32"
	FileSystemRamfs       FileSystem = "Ramfs"
	FileSystemSwap        FileSystem = "Swap"
	FileSystemTmpfs       FileSystem = "Tmpfs"
	FileSystemUnformatted FileSystem = "Unformatted"
	FileSystemUnknown     FileSystem = "Unknown"
	FileSystemVfat        FileSystem = "Vfat"
	FileSystemXfs         FileSystem = "Xfs"
	FileSystemZfsroot     FileSystem = "Zfsroot"
)

type HeaderTransport

type HeaderTransport struct {
	Transport http.RoundTripper
	Header    http.Header
}

HeaderTransport is a http.RoundTripper that adds some headers to all requests.

func (*HeaderTransport) CloseIdleConnections

func (h *HeaderTransport) CloseIdleConnections()

func (*HeaderTransport) RoundTrip

func (h *HeaderTransport) RoundTrip(req *http.Request) (*http.Response, error)

type ListMetadata

type ListMetadata struct {
	TotalCount int32 `json:"total_count"`
	Limit      int32 `json:"limit"`
	Skip       int32 `json:"skip"`
}

ListMetadata contains metadata about list responses

type ListMetalOptions

type ListMetalOptions struct {
	Skip  int32
	Limit int32

	Status    Status
	Region    string
	Tier      string
	Tag       string
	ProjectID int64
	TierType  MetalTierType
}

func (*ListMetalOptions) ToQueryParams

func (o *ListMetalOptions) ToQueryParams() []RequestOption

type ListMetalResponse

type ListMetalResponse Result[[]Metal]

Now we can update our response types to use the generic Result

type ListSshKeyResponse added in v2.0.2

type ListSshKeyResponse Result[[]SSHKey]

ListSshKeyResponse represents a response containing multiple SSH keys

type LogMessage

type LogMessage struct {
	Timestamp string `json:"timestamp"`
	Name      string `json:"name,omitempty"`
	Message   string `json:"message,omitempty"`
}

LogMessage represents a log entry for a metal service

type LogMessageResponse

type LogMessageResponse Result[[]LogMessage]

LogMessageResponse represents a response containing log messages

type MemoryOption

type MemoryOption struct {
	GB           int     `json:"gb"`           // Amount of memory in Gigabytes
	MonthlyPrice float64 `json:"monthlyPrice"` // Monthly price for this memory option
	HourlyPrice  float64 `json:"hourlyPrice"`  // Hourly price for this memory option
	Default      bool    `json:"default"`      // If this is the default memory option
}

MemoryOption represents a memory configuration option

type Metal

type Metal struct {
	ID          int64   `json:"id"`
	Created     string  `json:"created"`
	Deleted     *string `json:"deleted"`
	ObjectType  string  `json:"objectType"`
	ProjectID   int64   `json:"projectId"`
	DisplayName string  `json:"displayName"`

	// Service-specific fields
	RegionID   string     `json:"regionId"`
	Region     Region     `json:"region"`
	Status     Status     `json:"status"`
	PowerState PowerState `json:"powerState"`

	// Hardware configuration
	TierID         string                        `json:"tierId"`
	Tier           CpuDetails                    `json:"tier"`
	MemoryGB       int32                         `json:"memoryGb"`
	ImageID        string                        `json:"imageId"`
	StorageDevices map[string]MetalStorageDevice `json:"storageDevices"`

	// Network configuration
	IPAddresses []netip.Addr `json:"ipAddresses"`

	// Pricing
	MonthlyPrice float64 `json:"monthlyPrice"`
	HourlyPrice  float64 `json:"hourlyPrice"`

	// Additional metadata
	Tags   []string            `json:"tags"`
	Events []ProvisioningEvent `json:"events"`
}

Metal represents a bare metal service

type MetalConfiguration

type MetalConfiguration struct {
	Disks    map[string]string `json:"disks"`    // Dictionary of disk names and sizes
	MemoryGB int               `json:"memoryGb"` // Amount of memory in GB
	Tier     MetalTier         `json:"tier"`     // The tier configuration
	Quantity int               `json:"quantity"` // Available quantity
}

MetalConfiguration represents the availability configuration for metal services

type MetalConfigurationResponse

type MetalConfigurationResponse Result[[]MetalConfiguration]

MetalConfigurationResponse represents a response containing metal configuration data

type MetalResponse

type MetalResponse Result[Metal]

Now we can update our response types to use the generic Result

type MetalStorageDevice

type MetalStorageDevice struct {
	Name         string       `json:"name"`         // Name of the drive (e.g. "1.92t" or "960g")
	Default      bool         `json:"default"`      // True if this is the default drive for the tier
	Type         StorageType  `json:"type"`         // Type of storage (HDD, SSD, NVME)
	CapacityGB   int          `json:"capacityGb"`   // The capacity of the drive in Gigabytes
	Details      DriveDetails `json:"details"`      // Additional drive details
	MonthlyPrice float64      `json:"monthlyPrice"` // The monthly price for the specific drive
	HourlyPrice  float64      `json:"hourlyPrice"`  // The hourly price for the specific drive
	IsBossDrive  bool         `json:"isBossDrive"`  // True if this drive is a boss drive
	ID           string       `json:"id,omitempty"`
}

MetalStorageDevice describes a drive which can be installed in a drive slot

type MetalTier

type MetalTier struct {
	ID                 string                          `json:"id"`             // ID of the tier
	CPU                string                          `json:"cpu"`            // The CPU model for the tier
	CPUDescription     string                          `json:"cpuDescription"` // Description of CPU (cores/threads)
	ExternalIdentifier string                          `json:"externalIdentifier"`
	Hidden             bool                            `json:"hidden"`
	Availability       map[string]*ServiceAvailability `json:"availability"`
	MemoryOptions      []MemoryOption                  `json:"memoryOptions"`  // Available memory configurations
	DriveSlots         []DriveSlot                     `json:"driveSlots"`     // Available drive slots
	NetworkOptions     []NetworkOption                 `json:"networkOptions"` // Available network configurations
	MonthlyPrice       float64                         `json:"monthlyPrice"`   // The monthly price for the tier
	HourlyPrice        float64                         `json:"hourlyPrice"`    // The hourly price for the tier
	MemoryOptionSetID  int                             `json:"memoryOptionSetId"`
	DriveSlotSetID     int                             `json:"driveSlotSetId"`
	NetworkOptionSetID int                             `json:"networkOptionSetId"`
	TierType           MetalTierType                   `json:"tierType"`
}

MetalTier represents a hardware configuration tier for metal services

type MetalTierResponse

type MetalTierResponse Result[[]MetalTier]

Update the response type for ListMetalTiers

type MetalTierType

type MetalTierType string

MetalTierType represents the type of metal tier

const (
	MetalTierTypeCompute MetalTierType = "Compute"
	MetalTierTypeGPU     MetalTierType = "GPU"
)

type NetworkOption

type NetworkOption struct {
	SpeedGbps    int     `json:"speedGbps"`    // Speed in Gbps
	MonthlyPrice float64 `json:"monthlyPrice"` // Monthly price for this network option
	HourlyPrice  float64 `json:"hourlyPrice"`  // Hourly price for this network option
	Default      bool    `json:"default"`      // If this is the default option
	IsBonded     bool    `json:"isBonded"`     // If this network option is bonded
}

NetworkOption represents a network configuration option

type Partition

type Partition struct {
	Name      string `json:"name"`
	Device    string `json:"device"`
	SizeBytes *int64 `json:"sizeBytes,omitempty"`
}

type PowerCommand

type PowerCommand string
const (
	PowerCommandPowerOff PowerCommand = "PowerOff"
	PowerCommandPowerOn  PowerCommand = "PowerOn"
)

type PowerState

type PowerState string

PowerState represents the power state of a service

const (
	PowerStateOff       PowerState = "Off"
	PowerStateOn        PowerState = "On"
	PowerStateRebooting PowerState = "Rebooting"
	PowerStateUnknown   PowerState = "Unknown"
)

type ProvisioningEvent

type ProvisioningEvent struct {
	Priority  int32      `json:"priority"`
	Body      string     `json:"body,omitempty"`
	Timestamp time.Time  `json:"timestamp"`
	State     EventState `json:"state"`
}

ProvisioningEvent represents an event during service provisioning

type RaidArray

type RaidArray struct {
	Name       string     `json:"name"`
	Type       RaidType   `json:"type"`
	Members    []string   `json:"members"`
	FileSystem FileSystem `json:"filesystem"`
	MountPoint string     `json:"mountPoint"`
}

type RaidType

type RaidType string
const (
	RaidTypeNone    RaidType = "None"
	RaidTypeRaid0   RaidType = "Raid0"
	RaidTypeRaid1   RaidType = "Raid1"
	RaidTypeUnknown RaidType = "Unknown"
)

type Region added in v2.0.5

type Region struct {
	ID       *string `json:"id,omitempty"`
	Name     *string `json:"name,omitempty"`
	Country  *string `json:"country,omitempty"`
	City     *string `json:"city,omitempty"`
	Location *string `json:"location,omitempty"`
}

Region represents a region

type ReinstallMetalRequest added in v2.0.1

type ReinstallMetalRequest struct {
	DisplayName string      `json:"displayName,omitempty"`
	ImageID     string      `json:"imageId,omitempty"`
	SSHKeyIDs   []int64     `json:"sshKeyIds,omitempty"`
	Password    string      `json:"password,omitempty"`
	UserData    string      `json:"userData,omitempty"`
	IPXEUrl     string      `json:"ipxeUrl,omitempty"`
	Partitions  []Partition `json:"partitions,omitempty"`
	RaidArrays  []RaidArray `json:"raidArrays,omitempty"`
}

type RequestOption

type RequestOption func(*http.Request)

RequestOption is a function that can be used to modify an http.Request.

func WithQueryParam

func WithQueryParam(key, value string) RequestOption

WithQueryParam adds a query parameter to the request.

type Result

type Result[T any] struct {
	Success          bool         `json:"success"`
	Message          string       `json:"message,omitempty"`
	ValidationErrors []any        `json:"validationErrors,omitempty"`
	Metadata         ListMetadata `json:"metadata"`
	Result           T            `json:"result,omitempty"`
}

Result represents a standard API response with metadata and results

type SSHKey added in v2.0.2

type SSHKey struct {
	ID          int64   `json:"id"`
	Created     string  `json:"created"`
	Deleted     *string `json:"deleted,omitempty"`
	ObjectType  string  `json:"objectType"`  // The type of object (always "KEY")
	ProjectID   int64   `json:"projectId"`   // The project ID
	DisplayName string  `json:"displayName"` // The display name of the SSH key
	Key         string  `json:"key"`         // The SSH key content
}

SSHKey represents an SSH key

type ServiceAvailability

type ServiceAvailability struct {
	MaxQuantity int `json:"maxQuantity"`
}

ServiceAvailability represents the availability of a service in a region

type SshKeyResponse added in v2.0.2

type SshKeyResponse Result[SSHKey]

SshKeyResponse represents a response containing SSH key data

type Status

type Status string

Status represents the current status of a service

const (
	StatusPending    Status = "Pending"
	StatusActive     Status = "Active"
	StatusSuspended  Status = "Suspended"
	StatusTerminated Status = "Terminated"
	StatusError      Status = "Error"
)

type StorageType

type StorageType string

StorageType describes the storage type of the drive

const (
	StorageTypeHDD     StorageType = "HDD"
	StorageTypeSSD     StorageType = "SSD"
	StorageTypeNVME    StorageType = "NVME"
	StorageTypeUnknown StorageType = "Unknown"
)

Directories

Path Synopsis
examples
metal command
sshkey command

Jump to

Keyboard shortcuts

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