Documentation
¶
Overview ¶
Package sdk 提供 DevBridge 隧道服务的 Go 客户端: 隧道与端口的 REST API 管理,以及 Host 托管与 Connect 连接能力。
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" DefaultClusterID = "devbridge-s2" )
const AllPortsSentinel = -1
AllPortsSentinel 表示"所有端口"的哨兵值,对应后端存储的 -1。 它只对 visitor URL 访问有意义(网关按 SNI 动态路由任意端口), host/connect 的 SSH 主动端口转发不应转发该值。
Variables ¶
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: must be 8 chars of lowercase letters and digits 2-7")
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 判断 error 是否为 APIError,并返回错误码
Types ¶
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
// InsecureSkipVerify disables TLS certificate verification for the
// WebSocket connection to the gateway. Defaults to false (verify).
// Enable only for gateways whose certificate does not cover the tunnel
// domain (e.g. multi-level domains beyond a single-segment wildcard).
InsecureSkipVerify bool
// StatusWriter receives user-facing status lines (connection progress,
// hosted ports, forwarding info). Defaults to os.Stdout; set it to
// io.Discard to silence these outputs.
StatusWriter 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 // 隧道 ID
Ports []int // 端口列表(为空时从 Host 端通过 SSH 下发)
JWTToken string // JWT 令牌(与 APIKey 二选一)
APIKey string // API Key(与 JWTToken 二选一)
LocalIP string // 本地监听地址,默认 127.0.0.1
// OnReady 在会话就绪(本地端口映射建立)后调用,参数为本次建立的映射列表。
// 每次连接或重连成功都会触发一次。可为 nil。
OnReady func(forwardings []Forwarding)
}
ConnectConfig Connect 连接配置
type Devbridge ¶
type Devbridge struct {
// contains filtered or unexported fields
}
Devbridge DevBridge SDK 客户端
Example (Connect) ¶
package main
import (
"context"
"log"
"github.com/huaweicloud/devspace-devbridge/sdk"
)
func main() {
client := sdk.New(sdk.Config{APIKey: "your-api-key"})
// 连接隧道,在本地建立端口映射
// 连接成功后,http://localhost:8080 → 远端 Host 的 8080 端口
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/huaweicloud/devspace-devbridge/sdk"
)
func main() {
ctx := context.Background()
// 创建客户端(API Key 也可通过 HW_API_KEY 环境变量设置)
client := sdk.New(sdk.Config{APIKey: "your-api-key"})
// 1. 创建隧道
tunnel, err := client.CreateTunnel(ctx, "my-dev-tunnel", "开发联调环境", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("隧道已创建: %s\n", tunnel.ID)
// 2. 添加端口
allowAnon := true
if err := client.CreatePort(ctx, tunnel.ID, 8080, "http", &allowAnon); err != nil {
log.Fatal(err)
}
// 3. Host 托管(在服务所在设备运行)
//
// 这会阻塞,通常在单独的 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 退出: %v", err)
}
}()
time.Sleep(2 * time.Second) // 等待 Host 就绪
// 4. Connect 连接(在访问设备运行)
//
// 连接成功后,在访问设备上 http://localhost:8080 即可访问远端服务
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 退出: %v", err)
}
}()
time.Sleep(5 * time.Second)
// 5. 清理
connectCancel()
hostCancel()
client.DeleteTunnel(ctx, tunnel.ID)
}
Output:
Example (Host) ¶
package main
import (
"context"
"log"
"github.com/huaweicloud/devspace-devbridge/sdk"
)
func main() {
client := sdk.New(sdk.Config{APIKey: "your-api-key"})
// 查询隧道端口
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
}
// 启动 Host(阻塞)
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/huaweicloud/devspace-devbridge/sdk"
)
func main() {
client := sdk.New(sdk.Config{})
// 先签发 Host 令牌
token, err := client.IssueToken(context.Background(), "aaaadysa", "host")
if err != nil {
log.Fatal(err)
}
// 用令牌启动 Host,不再调用 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/huaweicloud/devspace-devbridge/sdk"
)
func main() {
ctx := context.Background()
client := sdk.New(sdk.Config{APIKey: "your-api-key"})
// 创建隧道,有效期 24 小时
exp := 24
tunnel, _ := client.CreateTunnel(ctx, "my-tunnel", "描述", &exp)
// 查询隧道列表
tunnels, _ := client.ListTunnels(ctx)
for _, t := range tunnels {
fmt.Printf("%s: %s\n", t.ID, t.Name)
}
// 查询隧道详情
detail, _ := client.ShowTunnel(ctx, tunnel.ID)
fmt.Printf("端口数: %d\n", detail.Status.HostConnectionCount)
// 更新隧道
newName := "renamed-tunnel"
client.UpdateTunnel(ctx, tunnel.ID, &newName, nil, nil)
// 删除隧道
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.
func (*Devbridge) Connect ¶
func (d *Devbridge) Connect(ctx context.Context, cfg ConnectConfig) error
Connect 启动 Connect 连接服务。
这是一个阻塞方法,在 ctx 被取消或连接彻底断开时返回;网络短暂中断会自动重连。
func (*Devbridge) CreatePort ¶
func (d *Devbridge) CreatePort(ctx context.Context, tunnelID string, port int, protocol string, allowAnonymous *bool) error
CreatePort 在隧道上创建端口
func (*Devbridge) CreateTunnel ¶
func (d *Devbridge) CreateTunnel(ctx context.Context, name, description string, expiration *int) (*Tunnel, error)
CreateTunnel 创建隧道,expiration 为 nil 时使用默认有效期 72 小时
func (*Devbridge) DeletePort ¶
DeletePort 删除端口
func (*Devbridge) DeleteTunnel ¶
DeleteTunnel 删除指定隧道
func (*Devbridge) Host ¶
func (d *Devbridge) Host(ctx context.Context, cfg HostConfig) error
Host 启动 Host 托管服务。
这是一个阻塞方法,在 ctx 被取消或连接彻底断开时返回;网络短暂中断会自动重连。
工作流程:
- WebSocket 连到 wss://<tunnelId>.<gatewayHost>/<tunnelId>
- 在 WebSocket 上建立 SSH 会话
- 接受 relay channel,为每个 channel 创建内层 SSH 会话
- 通过端口转发把流量从远端转到本地端口
func (*Devbridge) IssueToken ¶
IssueToken 签发隧道令牌,scope 必须是 "host" 或 "connect"
func (*Devbridge) ListTunnels ¶
ListTunnels 查询当前工作空间的有效隧道列表
func (*Devbridge) ShowTunnel ¶
ShowTunnel 查询隧道详情
type Forwarding ¶
Forwarding 端口转发映射信息
type HostConfig ¶
type HostConfig struct {
TunnelID string // 隧道 ID
Ports []int // 本地端口列表(为空时从网关下发)
JWTToken string // JWT 令牌(与 APIKey 二选一)
APIKey string // API Key(与 JWTToken 二选一)
// OnReady 在会话就绪(端口开始转发)后调用,参数为本次托管的端口列表。
// 每次连接或重连成功都会触发一次。可为 nil。
OnReady func(ports []int)
}
HostConfig Host 托管配置
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 配额
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 端口配置
type Tunnel ¶
type Tunnel struct {
ID string `json:"tunnelId"` // 8 位小写 Base32
Name string `json:"name"`
Description string `json:"description"`
ExpirationHours int `json:"expirationHours"` // 有效期(小时)
TunnelExpiration uint32 `json:"tunnelExpiration"` // 过期时间(Unix 秒)
PortCount int `json:"portCount"`
}
Tunnel 隧道
type TunnelDetail ¶
type TunnelDetail struct {
Name string `json:"name"`
ID string `json:"tunnelId"`
TunnelExpiration uint32 `json:"tunnelExpiration"` // Unix 秒
Description string `json:"description"`
Status *TunnelStatus `json:"status,omitempty"`
}
TunnelDetail 隧道详情(含状态)
type TunnelStatus ¶
type TunnelStatus struct {
ClientConnectionCount int `json:"clientConnectionCount"`
HostConnectionCount int `json:"hostConnectionCount"`
TotalUploadBytes int64 `json:"totalUploadBytes"`
TotalDownloadBytes int64 `json:"totalDownloadBytes"`
}
TunnelStatus 隧道运行状态
type TunnelToken ¶
type TunnelToken struct {
TunnelID string `json:"tunnelId"`
Scope string `json:"scope"` // host 或 connect
Token string `json:"token"` // JWT
}
TunnelToken 隧道令牌
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
httpclient
Package httpclient 实现 DevBridge REST API 的底层 HTTP 通信。
|
Package httpclient 实现 DevBridge REST API 的底层 HTTP 通信。 |