sdk

package module
v0.1.0-release Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

DevBridge Go SDK

中文文档:README.zh-CN.md

DevBridge is Huawei Cloud's development tunnel service. It connects Host (local service hosting) with Connect (remote connection) via a relay, enabling local services to be accessed remotely without a public inbound port.

This SDK wraps the core capabilities of the DevBridge CLI as a Go API.

Features

  • Tunnel management: create, query, update, and delete tunnels
  • Port management: create, query, update, and delete ports
  • Token issuance: issue Host / Connect tokens
  • Host hosting: forward local ports to the DevBridge relay via a WebSocket + SSH tunnel
  • Connect connection: connect to a tunnel and establish local port mappings to access remote services

Installation

Requires Go 1.22 or above.

go get github.com/huaweicloud/devspace-devbridge/go-sdk@v0.1.0

Quick Start

Full flow: create tunnel → Host hosting → Connect connection
package main

import (
	"context"
	"log"

	"github.com/huaweicloud/devspace-devbridge/go-sdk"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	client := sdk.New(sdk.Config{APIKey: "your-api-key"})

	// 1. Create tunnel
	tunnel, err := client.CreateTunnel(ctx, "my-tunnel", "dev-debug", nil)
	if err != nil {
		log.Fatal(err)
	}

	// 2. Add port
	allowAnon := true
	if err := client.CreatePort(ctx, tunnel.ID, 8080, "http", &allowAnon); err != nil {
		log.Fatal(err)
	}

	// 3. Host hosting (on the device running the service)
	//    Receive ready notification via OnReady, no polling needed
	go func() {
		err := client.Host(ctx, sdk.HostConfig{
			TunnelID: tunnel.ID,
			Ports:    []int{8080},
			OnReady: func(ports []int) {
				log.Println("Host ready, hosted ports:", ports)
			},
		})
		if err != nil {
			log.Println("Host exited:", err)
		}
	}()

	// 4. Connect connection (on the accessing device)
	//    After connecting, http://localhost:8080 → remote service
	err = client.Connect(ctx, sdk.ConnectConfig{
		TunnelID: tunnel.ID,
		Ports:    []int{8080},
	})
	if err != nil {
		log.Fatal(err)
	}
}
Host hosting only
// Blocking run; stop with Ctrl+C / cancel context
err := client.Host(ctx, sdk.HostConfig{
	TunnelID: "aaaadysa",
	Ports:    []int{8080, 3000},
})
Connect connection only
// Blocking run; after connecting, localhost:8080 → remote
err := client.Connect(ctx, sdk.ConnectConfig{
	TunnelID: "aaaadysa",
	Ports:    []int{8080},
})
Using a JWT token (skip API calls)
token, err := client.IssueToken(ctx, "aaaadysa", "host")
if err != nil {
	log.Fatal(err)
}

err = client.Host(ctx, sdk.HostConfig{
	TunnelID: "aaaadysa",
	JWTToken: token.Token,
})

Examples

For more complete runnable examples, see example_test.go, covering:

  • Full flow: create tunnel → add port → Host hosting → Connect connection
  • Host hosting with an existing tunnel
  • Using a JWT token (skip API calls)
  • Connect connection and access to remote services
  • Tunnel management

API Reference

For complete type and method documentation, see pkg.go.dev.

Client configuration
client := sdk.New(sdk.Config{
	APIKey:      "your-key",   // API Key; reads HW_API_KEY env var when empty
	APIBaseURL:  "custom-url", // Custom REST API address
	GatewayAddr: "addr:443",   // Custom gateway address
	GatewayHost: "host",       // Custom gateway SNI host
	OutputWriter: io.Discard,  // Status output destination; defaults to os.Stdout; io.Discard silences it
})
Tunnel management
Method Description
CreateTunnel(ctx, name, desc, *expiration) Create a tunnel; the description supports only Chinese characters/letters/digits (0-64 chars)
ListTunnels(ctx) List tunnels
ShowTunnel(ctx, id) Show tunnel details
UpdateTunnel(ctx, id, *name, *desc, *exp) Update a tunnel
DeleteTunnel(ctx, id) Delete a tunnel
DeleteAllTunnels(ctx) Delete all tunnels
IssueToken(ctx, id, scope) Issue a token (scope: "host" / "connect")
GetLimits(ctx) Query quotas
Port management
Method Description
CreatePort(ctx, tunnelID, port, protocol, *allowAnon) Create a port
ListPorts(ctx, tunnelID) List ports
ShowPort(ctx, tunnelID, port) Show port details
UpdatePort(ctx, tunnelID, port, *allowAnon) Update a port
DeletePort(ctx, tunnelID, port) Delete a port
Host / Connect
Method Description
Host(ctx, HostConfig) Host local ports (blocking)
Connect(ctx, ConnectConfig) Connect to a remote tunnel (blocking)

Common fields of HostConfig / ConnectConfig:

Field Description
Ports Port list; when empty for Host, delivered from the gateway; when empty for Connect, negotiated with Host via SSH
JWTToken / APIKey Choose one; skips the SDK's internal token issuance
LocalIP (Connect only) Local listen address, defaults to 127.0.0.1
OnReady Session-ready callback: Host returns the hosted port list, Connect returns the port mapping list

Error handling

err := client.Host(ctx, cfg)
if err != nil {
	switch {
	case errors.Is(err, sdk.ErrMissingAPIKey):
		// Missing API Key
	case errors.Is(err, sdk.ErrTunnelNotFound):
		// Tunnel not found
	case errors.Is(err, sdk.ErrDuplicateHost):
		// A Host is already running
	case errors.Is(err, sdk.ErrQuotaExceeded):
		// Quota exceeded
	case errors.Is(err, sdk.ErrInvalidTunnelID):
		// Invalid tunnel ID format
	case errors.Is(err, sdk.ErrInvalidTunnelDescription):
		// Invalid tunnel description (Chinese chars/letters/digits only, 0-64 chars)
	case errors.Is(err, sdk.ErrInvalidPort):
		// Invalid port number
	default:
		// Other error
	}

	// Check API business errors
	if code, ok := sdk.IsAPIError(err); ok {
		fmt.Println("Error code:", code) // e.g. "HD.98320078"
	}
}

Architecture

Device A (Host)                       Device B (Connect)
┌───────────────┐                     ┌────────────────┐
│ Local service │                     │ Visitor        │
│ :8080         │                     │ localhost:8080 │
└───────┬───────┘                     └───────┬────────┘
        │                                     │
   ┌────┴────┐                           ┌─────┴─────┐
   │ Host    │                           │ Connect   │
   │ (SDK)   │                           │ (SDK)     │
   └────┬────┘                           └─────┴─────┘
        │ WebSocket outbound                 │ WebSocket outbound
        └───────────┐     ┌───────────────────┘
                    ▼     ▼
              ┌─────────────────┐
              │ DevBridge relay │
              │ (SSH over WS)   │
              └─────────────────┘

Both Host and Connect actively connect to the DevBridge relay, so the device running Host does not need to open a public inbound port.

Dependencies

  • github.com/coder/websocket — WebSocket client
  • github.com/microsoft/dev-tunnels-ssh — SSH tunnel protocol

Changelog

See CHANGELOG.md.

License

Apache License 2.0

Documentation

Overview

Package sdk provides a Go client for the DevBridge tunnel service: REST API management for tunnels and ports, plus Host hosting and Connect connection capabilities.

Index

Examples

Constants

View Source
const (
	DefaultAPIBaseURL  = "https://bridge.developer.myhuaweicloud.com"
	DefaultGatewayAddr = "gateway.devbridge-s2.hwtunnel.com:443"
	DefaultGatewayHost = "devbridge-s2.hwtunnel.com"
)
View Source
const AllPortsSentinel = -1

AllPortsSentinel is the "all ports" sentinel value, corresponding to -1 in the backend. It only matters for visitor URL access (the gateway routes any port by SNI); host/connect SSH port forwarding must not forward this value.

Variables

View Source
var DefaultClusterID = "devbridge-s2"

DefaultClusterID is the cluster used when creating new tunnels. It is a var (not const) so builds can override it via ldflags (-X github.com/huaweicloud/devspace-devbridge/go-sdk.DefaultClusterID=...).

View Source
var ErrDuplicateHost = errors.New("host already connected for this tunnel")
View Source
var ErrInvalidPort = errors.New("invalid port number: must be 1-65535")
View Source
var ErrInvalidProtocol = errors.New("invalid protocol: must be http, https, or auto")
View Source
var ErrInvalidScope = errors.New("invalid token scope: must be host or connect")
View Source
var ErrInvalidTunnelDescription = errors.New("invalid tunnel description: only Chinese characters, letters, digits, length 0-64")
View Source
var ErrInvalidTunnelID = errors.New("invalid tunnel id")
View Source
var ErrInvalidTunnelName = errors.New("invalid tunnel name: only Chinese characters, letters, digits, hyphens, length 1-64")
View Source
var ErrMissingAPIKey = errors.New("missing API key: set it via Config.APIKey or HW_API_KEY env var")
View Source
var ErrQuotaExceeded = errors.New("account quota exceeded")
View Source
var ErrTunnelNotFound = errors.New("tunnel not found")

Functions

func IsAPIError

func IsAPIError(err error) (code string, ok bool)

IsAPIError reports whether err is an APIError and returns its code.

func IsUpgradeRequired

func IsUpgradeRequired(err error) bool

IsUpgradeRequired reports whether err indicates an upgrade-required response.

Types

type APIError

type APIError = httpclient.APIError

APIError represents a business error returned by the server.

type Config

type Config struct {
	// APIKey authenticates REST API requests (X-API-Key header).
	// Defaults to HW_API_KEY environment variable.
	APIKey string

	// APIBaseURL is the REST API base URL.
	// Defaults to DefaultAPIBaseURL.
	APIBaseURL string

	// GatewayAddr is the WebSocket gateway address (host:port).
	// Defaults to DefaultGatewayAddr.
	GatewayAddr string

	// GatewayHost is the WebSocket gateway SNI host.
	// Defaults to DefaultGatewayHost.
	GatewayHost string

	// WSHeaders are extra headers merged into every WebSocket handshake
	// (host/connect). The SDK does not interpret them; it only forwards them,
	// so a caller like the CLI can inject e.g. a User-Agent without the SDK
	// knowing its meaning. A nil map adds nothing.
	WSHeaders http.Header

	// OutputWriter receives user-facing output (connection progress,
	// hosted ports, forwarding info). Defaults to os.Stdout; set it to
	// io.Discard to silence these outputs.
	OutputWriter io.Writer

	// HTTPClient, when non-nil, is used for REST API requests instead of the
	// SDK default client. It allows the caller (e.g. the CLI) to inject a
	// custom transport or headers without changing other SDK behavior.
	HTTPClient *http.Client
}

Config holds the SDK client configuration. A zero Config is valid — missing fields fall back to environment variables and sensible defaults.

type ConnectConfig

type ConnectConfig struct {
	TunnelID string // tunnel ID
	Ports    []int  // ports to forward (empty means delivered by the host via SSH)
	JWTToken string // JWT token (mutually exclusive with APIKey)
	APIKey   string // API key (mutually exclusive with JWTToken)
	LocalIP  string // local listen address, defaults to 127.0.0.1

	// OnReady is called once the session is ready (local port mappings established), with the list of mappings.
	// It fires once per established connection or reconnect. May be nil.
	OnReady func(forwardings []Forwarding)
}

ConnectConfig is the configuration for connecting to a tunnel.

type Devbridge

type Devbridge struct {
	// contains filtered or unexported fields
}

Devbridge is the DevBridge SDK client.

Example (Connect)
package main

import (
	"context"
	"log"

	"github.com/huaweicloud/devspace-devbridge/go-sdk"
)

func main() {
	client := sdk.New(sdk.Config{APIKey: "your-api-key"})

	// Connect to the tunnel and set up local port mappings
	// After connecting, http://localhost:8080 -> port 8080 of the remote host
	err := client.Connect(context.Background(), sdk.ConnectConfig{
		TunnelID: "aaaadysa",
		Ports:    []int{8080},
	})
	if err != nil {
		log.Fatal(err)
	}
}
Example (FullWorkflow)
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/huaweicloud/devspace-devbridge/go-sdk"
)

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

	// Create the client (the API key can also be set via the HW_API_KEY env var)
	client := sdk.New(sdk.Config{APIKey: "your-api-key"})

	// 1. Create a tunnel
	tunnel, err := client.CreateTunnel(ctx, "my-dev-tunnel", "dev/test environment", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("tunnel created: %s\n", tunnel.ID)

	// 2. Add a port
	allowAnon := true
	if err := client.CreatePort(ctx, tunnel.ID, 8080, "http", &allowAnon); err != nil {
		log.Fatal(err)
	}

	// 3. Host: run on the device where the service lives
	//
	// This blocks, so it usually runs in a separate goroutine:
	hostCtx, hostCancel := context.WithCancel(context.Background())
	go func() {
		if err := client.Host(hostCtx, sdk.HostConfig{
			TunnelID: tunnel.ID,
			Ports:    []int{8080},
		}); err != nil {
			log.Printf("host exited: %v", err)
		}
	}()

	time.Sleep(2 * time.Second) // wait for Host to be ready

	// 4. Connect: run on the accessing device
	//
	// After connecting, http://localhost:8080 on the accessing device reaches the remote service
	connectCtx, connectCancel := context.WithCancel(context.Background())
	go func() {
		if err := client.Connect(connectCtx, sdk.ConnectConfig{
			TunnelID: tunnel.ID,
			Ports:    []int{8080},
		}); err != nil {
			log.Printf("connect exited: %v", err)
		}
	}()

	time.Sleep(5 * time.Second)

	// 5. Cleanup
	connectCancel()
	hostCancel()
	_ = client.DeleteTunnel(ctx, tunnel.ID)
}
Example (Host)
package main

import (
	"context"
	"log"

	"github.com/huaweicloud/devspace-devbridge/go-sdk"
)

func main() {
	client := sdk.New(sdk.Config{APIKey: "your-api-key"})

	// List the tunnel's ports
	ports, err := client.ListPorts(context.Background(), "aaaadysa")
	if err != nil {
		log.Fatal(err)
	}

	portList := make([]int, len(ports))
	for i, p := range ports {
		portList[i] = p.Port
	}

	// Start the host (blocks)
	err = client.Host(context.Background(), sdk.HostConfig{
		TunnelID: "aaaadysa",
		Ports:    portList,
	})
	if err != nil {
		log.Fatal(err)
	}
}
Example (HostWithToken)
package main

import (
	"context"
	"log"

	"github.com/huaweicloud/devspace-devbridge/go-sdk"
)

func main() {
	client := sdk.New(sdk.Config{})

	// Issue a host token first
	token, err := client.IssueToken(context.Background(), "aaaadysa", "host")
	if err != nil {
		log.Fatal(err)
	}

	// Start the host with the token, without calling the REST API
	err = client.Host(context.Background(), sdk.HostConfig{
		TunnelID: "aaaadysa",
		JWTToken: token.Token,
	})
	if err != nil {
		log.Fatal(err)
	}
}
Example (TunnelManagement)
package main

import (
	"context"
	"fmt"

	"github.com/huaweicloud/devspace-devbridge/go-sdk"
)

func main() {
	ctx := context.Background()
	client := sdk.New(sdk.Config{APIKey: "your-api-key"})

	// Create a tunnel with 24-hour validity
	exp := 24
	tunnel, _ := client.CreateTunnel(ctx, "my-tunnel", "description", &exp)

	// List tunnels
	tunnels, _ := client.ListTunnels(ctx)
	for _, t := range tunnels {
		fmt.Printf("%s: %s\n", t.ID, t.Name)
	}

	// Get tunnel details
	detail, _ := client.ShowTunnel(ctx, tunnel.ID)
	if detail.Status != nil {
		fmt.Printf("port count: %d\n", detail.Status.HostConnectionCount)
	}

	// Update the tunnel
	newName := "renamed-tunnel"
	_ = client.UpdateTunnel(ctx, tunnel.ID, &newName, nil, nil)

	// Delete the tunnel
	_ = client.DeleteTunnel(ctx, tunnel.ID)
}

func New

func New(cfg Config) *Devbridge

New creates a new SDK client from the given Config. A zero Config is valid; APIKey falls back to HW_API_KEY env var, and other fields fall back to sensible defaults.

As part of initialization it starts a background DNS lookup for the gateway address to warm the OS resolver cache, and installs a shared TLS session cache so reconnects reuse TLS session tickets instead of re-negotiating from scratch.

func (*Devbridge) Connect

func (d *Devbridge) Connect(ctx context.Context, cfg ConnectConfig) error

Connect starts the Connect connection service.

This is a blocking call that returns when ctx is canceled or the connection is fully lost; brief network interruptions are reconnected automatically.

func (*Devbridge) CreatePort

func (d *Devbridge) CreatePort(ctx context.Context, tunnelID string, port int, protocol string, allowAnonymous *bool) error

CreatePort creates a port on a tunnel.

func (*Devbridge) CreateTunnel

func (d *Devbridge) CreateTunnel(ctx context.Context, name, description string, expiration *int) (*Tunnel, error)

CreateTunnel creates a tunnel; a nil expiration uses the default 72-hour validity.

func (*Devbridge) DeleteAllTunnels

func (d *Devbridge) DeleteAllTunnels(ctx context.Context) error

DeleteAllTunnels deletes all tunnels in the current workspace.

Use with caution: this deletes every tunnel.

func (*Devbridge) DeletePort

func (d *Devbridge) DeletePort(ctx context.Context, tunnelID string, port int) error

DeletePort deletes a port.

func (*Devbridge) DeleteTunnel

func (d *Devbridge) DeleteTunnel(ctx context.Context, tunnelID string) error

DeleteTunnel deletes the specified tunnel.

func (*Devbridge) GetLimits

func (d *Devbridge) GetLimits(ctx context.Context) (*Limits, error)

GetLimits returns the current quota.

func (*Devbridge) Host

func (d *Devbridge) Host(ctx context.Context, cfg HostConfig) error

Host starts the Host hosting service.

This is a blocking call that returns when ctx is canceled or the connection is fully lost; brief network interruptions are reconnected automatically.

Workflow:

  1. Connect WebSocket to wss://<tunnelId>.<gatewayHost>/<tunnelId>
  2. Establish an SSH session over the WebSocket
  3. Accept relay channels and create an inner SSH session for each
  4. Forward traffic from the remote side to the local port

func (*Devbridge) IssueToken

func (d *Devbridge) IssueToken(ctx context.Context, tunnelID, scope string) (*TunnelToken, error)

IssueToken issues a tunnel token; scope must be "host" or "connect".

func (*Devbridge) ListPorts

func (d *Devbridge) ListPorts(ctx context.Context, tunnelID string) ([]Port, error)

ListPorts lists the ports of a tunnel.

func (*Devbridge) ListTunnels

func (d *Devbridge) ListTunnels(ctx context.Context) ([]Tunnel, error)

ListTunnels lists the active tunnels in the current workspace.

func (*Devbridge) ShowPort

func (d *Devbridge) ShowPort(ctx context.Context, tunnelID string, port int) (*Port, error)

ShowPort returns the details of a port.

func (*Devbridge) ShowTunnel

func (d *Devbridge) ShowTunnel(ctx context.Context, tunnelID string) (*TunnelDetail, error)

ShowTunnel returns the details of a tunnel.

func (*Devbridge) UpdatePort

func (d *Devbridge) UpdatePort(ctx context.Context, tunnelID string, port int, allowAnonymous *bool) error

UpdatePort updates the anonymous access policy of a port; a nil allowAnonymous leaves it unchanged.

func (*Devbridge) UpdateTunnel

func (d *Devbridge) UpdateTunnel(ctx context.Context, tunnelID string, name, description *string, expiration *int) error

UpdateTunnel updates a tunnel; only non-nil fields are modified.

type Forwarding

type Forwarding struct {
	LocalPort  int    // local port
	RemotePort int    // remote port
	LocalIP    string // local listen address
}

Forwarding describes a port forwarding mapping.

type HostConfig

type HostConfig struct {
	TunnelID string // tunnel ID
	Ports    []int  // local ports to forward (empty means issued by the gateway)
	JWTToken string // JWT token (mutually exclusive with APIKey)
	APIKey   string // API key (mutually exclusive with JWTToken)

	// OnReady runs once the session is ready, with the hosted ports. May be nil.
	OnReady func(ports []int)
}

HostConfig is the configuration for hosting a tunnel.

type Limits

type Limits struct {
	ResetAt                          int64 `json:"resetAt"`
	QuotaBytes                       int64 `json:"quotaBytes"`
	RemainingBytes                   int64 `json:"remainingBytes"`
	ActiveTunnels                    int64 `json:"activeTunnels"`
	MaxTunnels                       int32 `json:"maxTunnels"`
	MaxPortsPerTunnel                int32 `json:"maxPortsPerTunnel"`
	MaxHostsPerTunnel                int32 `json:"maxHostsPerTunnel"`
	MaxTunnelBandwidthBytesPerSecond int64 `json:"maxTunnelBandwidthBytesPerSecond"`
	MaxHTTPRequestsPerMinutePerPort  int32 `json:"maxHttpRequestsPerMinutePerPort"`
	MaxConnectionsPerPort            int32 `json:"maxConnectionsPerPort"`
}

Limits represents the quota.

type Port

type Port struct {
	TunnelID       string `json:"tunnelId"`
	Port           int    `json:"port"`
	Protocol       string `json:"protocol"` // http, https, auto
	AllowAnonymous bool   `json:"allowAnonymous"`
}

Port represents a port configuration.

type Tunnel

type Tunnel struct {
	ID               string `json:"tunnelId"` // 8-char lowercase Base32
	Name             string `json:"name"`
	Description      string `json:"description"`
	ExpirationHours  int    `json:"expirationHours"`  // validity in hours
	TunnelExpiration uint32 `json:"tunnelExpiration"` // expiration time (Unix seconds)
	PortCount        int    `json:"portCount"`
}

Tunnel represents a tunnel.

type TunnelDetail

type TunnelDetail struct {
	Name             string        `json:"name"`
	ID               string        `json:"tunnelId"`
	TunnelExpiration uint32        `json:"tunnelExpiration"` // Unix seconds
	Description      string        `json:"description"`
	Status           *TunnelStatus `json:"status,omitempty"`
}

TunnelDetail represents tunnel details including status.

type TunnelStatus

type TunnelStatus struct {
	ClientConnectionCount int   `json:"clientConnectionCount"`
	HostConnectionCount   int   `json:"hostConnectionCount"`
	TotalUploadBytes      int64 `json:"totalUploadBytes"`
	TotalDownloadBytes    int64 `json:"totalDownloadBytes"`
}

TunnelStatus represents the runtime status of a tunnel.

type TunnelToken

type TunnelToken struct {
	TunnelID string `json:"tunnelId"`
	Scope    string `json:"scope"` // "host" or "connect"
	Token    string `json:"token"` // JWT
}

TunnelToken represents a tunnel token.

type UpgradeRequiredError

type UpgradeRequiredError = httpclient.UpgradeRequiredError

UpgradeRequiredError indicates the server rejected a request because the client version is below the required minimum (HTTP 426 Upgrade Required).

Directories

Path Synopsis
internal
httpclient
Package httpclient implements the low-level HTTP communication for the DevBridge REST API.
Package httpclient implements the low-level HTTP communication for the DevBridge REST API.
i18n
Package i18n provides minimal bilingual (zh/en) message support for the SDK's user-facing terminal output.
Package i18n provides minimal bilingual (zh/en) message support for the SDK's user-facing terminal output.

Jump to

Keyboard shortcuts

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