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 ¶
- Constants
- Variables
- func IsAPIError(err error) (code string, ok bool)
- type APIError
- type Config
- type ConnectConfig
- type Devbridge
- func (d *Devbridge) Connect(ctx context.Context, cfg ConnectConfig) error
- func (d *Devbridge) CreatePort(ctx context.Context, tunnelID string, port int, protocol string, ...) error
- func (d *Devbridge) CreateTunnel(ctx context.Context, name, description string, expiration *int) (*Tunnel, error)
- func (d *Devbridge) DeleteAllTunnels(ctx context.Context) error
- func (d *Devbridge) DeletePort(ctx context.Context, tunnelID string, port int) error
- func (d *Devbridge) DeleteTunnel(ctx context.Context, tunnelID string) error
- func (d *Devbridge) GetLimits(ctx context.Context) (*Limits, error)
- func (d *Devbridge) Host(ctx context.Context, cfg HostConfig) error
- func (d *Devbridge) IssueToken(ctx context.Context, tunnelID, scope string) (*TunnelToken, error)
- func (d *Devbridge) ListPorts(ctx context.Context, tunnelID string) ([]Port, error)
- func (d *Devbridge) ListTunnels(ctx context.Context) ([]Tunnel, error)
- func (d *Devbridge) ShowPort(ctx context.Context, tunnelID string, port int) (*Port, error)
- func (d *Devbridge) ShowTunnel(ctx context.Context, tunnelID string) (*TunnelDetail, error)
- func (d *Devbridge) UpdatePort(ctx context.Context, tunnelID string, port int, allowAnonymous *bool) error
- func (d *Devbridge) UpdateTunnel(ctx context.Context, tunnelID string, name, description *string, ...) error
- type Forwarding
- type HostConfig
- type Limits
- type Port
- type Tunnel
- type TunnelDetail
- type TunnelStatus
- type TunnelToken
Examples ¶
Constants ¶
const ( DefaultAPIBaseURL = "https://bridge.developer.myhuaweicloud.com/open-api-inner/v1/relay-controller" DefaultGatewayAddr = "gateway.devbridge-s2.hwtunnel.com:443" DefaultGatewayHost = "devbridge-s2.hwtunnel.com" )
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 ¶
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/17673651504/devspace-devbridge/go-sdk.DefaultClusterID=...).
var ErrDuplicateHost = errors.New("host already connected for this tunnel")
var ErrInvalidPort = errors.New("invalid port number: must be 1-65535")
var ErrInvalidProtocol = errors.New("invalid protocol: must be http, https, or auto")
var ErrInvalidScope = errors.New("invalid token scope: must be host or connect")
var ErrInvalidTunnelDescription = errors.New("invalid tunnel description: only Chinese characters, letters, digits, length 0-64")
var ErrInvalidTunnelID = errors.New("invalid tunnel id")
var ErrInvalidTunnelName = errors.New("invalid tunnel name: only Chinese characters, letters, digits, hyphens, length 1-64")
var ErrMissingAPIKey = errors.New("missing API key: set it via Config.APIKey or HW_API_KEY env var")
var ErrQuotaExceeded = errors.New("account quota exceeded")
var ErrTunnelNotFound = errors.New("tunnel not found")
Functions ¶
func IsAPIError ¶
IsAPIError reports whether err is an APIError and returns its code.
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
// 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
}
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/17673651504/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)
}
}
Output:
Example (FullWorkflow) ¶
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/17673651504/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)
}
Output:
Example (Host) ¶
package main
import (
"context"
"log"
"github.com/17673651504/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)
}
}
Output:
Example (HostWithToken) ¶
package main
import (
"context"
"log"
"github.com/17673651504/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)
}
}
Output:
Example (TunnelManagement) ¶
package main
import (
"context"
"fmt"
"github.com/17673651504/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)
}
Output:
func New ¶
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 ¶
DeleteAllTunnels deletes all tunnels in the current workspace.
Use with caution: this deletes every tunnel.
func (*Devbridge) DeletePort ¶
DeletePort deletes a port.
func (*Devbridge) DeleteTunnel ¶
DeleteTunnel deletes the specified tunnel.
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:
- Connect WebSocket to wss://<tunnelId>.<gatewayHost>/<tunnelId>
- Establish an SSH session over the WebSocket
- Accept relay channels and create an inner SSH session for each
- Forward traffic from the remote side to the local port
func (*Devbridge) IssueToken ¶
IssueToken issues a tunnel token; scope must be "host" or "connect".
func (*Devbridge) ListTunnels ¶
ListTunnels lists the active tunnels in the current workspace.
func (*Devbridge) ShowTunnel ¶
ShowTunnel returns the details of a tunnel.
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.
Source Files
¶
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. |