sdk

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: Apache-2.0 Imports: 21 Imported by: ? 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

DevBridge 是华为云的开发隧道服务,通过中继连接 Host(本地服务托管)与 Connect(远端连接),使本地服务无需公网入站端口即可被远程访问。

本 SDK 把 DevBridge CLI 的核心能力封装为 Go API。

特性

  • 隧道管理:创建、查询、更新、删除隧道
  • 端口管理:创建、查询、更新、删除端口
  • 令牌签发:签发 Host / Connect 令牌
  • Host 托管:把本地端口通过 WebSocket + SSH 隧道转发到 DevBridge 中继
  • Connect 连接:连接隧道,在本地建立端口映射访问远端服务

安装

要求 Go 1.22 及以上版本。

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

快速开始

完整流程:创建隧道 → Host 托管 → Connect 连接
package main

import (
	"context"
	"log"

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

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

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

	// 1. 创建隧道
	tunnel, err := client.CreateTunnel(ctx, "my-tunnel", "开发联调", nil)
	if err != nil {
		log.Fatal(err)
	}

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

	// 3. Host 托管(在服务所在设备)
	//    通过 OnReady 获得就绪通知,无需轮询等待
	go func() {
		err := client.Host(ctx, sdk.HostConfig{
			TunnelID: tunnel.ID,
			Ports:    []int{8080},
			OnReady: func(ports []int) {
				log.Println("Host 就绪,托管端口:", ports)
			},
		})
		if err != nil {
			log.Println("Host 退出:", err)
		}
	}()

	// 4. Connect 连接(在访问设备)
	//    连接后 http://localhost:8080 → 远端服务
	err = client.Connect(ctx, sdk.ConnectConfig{
		TunnelID: tunnel.ID,
		Ports:    []int{8080},
	})
	if err != nil {
		log.Fatal(err)
	}
}
仅 Host 托管
// 阻塞运行,Ctrl+C / cancel context 停止
err := client.Host(ctx, sdk.HostConfig{
	TunnelID: "aaaadysa",
	Ports:    []int{8080, 3000},
})
仅 Connect 连接
// 阻塞运行,连接后 localhost:8080 → 远端
err := client.Connect(ctx, sdk.ConnectConfig{
	TunnelID: "aaaadysa",
	Ports:    []int{8080},
})
使用 JWT 令牌(跳过 API 调用)
token, err := client.IssueToken(ctx, "aaaadysa", "host")
if err != nil {
	log.Fatal(err)
}

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

示例

更完整的可运行示例见 example_test.go,涵盖:

  • 完整流程:创建隧道 → 添加端口 → Host 托管 → Connect 连接
  • 使用已有隧道 Host 托管
  • 使用 JWT 令牌(跳过 API 调用)
  • Connect 连接并访问远端服务
  • 隧道管理

API 参考

完整的类型与方法文档见 pkg.go.dev。

客户端配置
client := sdk.New(sdk.Config{
	APIKey:      "your-key",   // API Key,留空时读取 HW_API_KEY 环境变量
	APIBaseURL:  "custom-url", // 自定义 REST API 地址
	GatewayAddr: "addr:443",   // 自定义网关地址
	GatewayHost: "host",       // 自定义网关 SNI host
	OutputWriter: io.Discard,  // 状态输出目的地,默认 os.Stdout,io.Discard 表示静音
})
隧道管理
方法 说明
CreateTunnel(ctx, name, desc, *expiration) 创建隧道,描述仅支持中文/字母/数字(0-64 字符)
ListTunnels(ctx) 查询隧道列表
ShowTunnel(ctx, id) 查询隧道详情
UpdateTunnel(ctx, id, *name, *desc, *exp) 更新隧道
DeleteTunnel(ctx, id) 删除隧道
DeleteAllTunnels(ctx) 删除全部隧道
IssueToken(ctx, id, scope) 签发令牌(scope: "host" / "connect")
GetLimits(ctx) 查询配额
端口管理
方法 说明
CreatePort(ctx, tunnelID, port, protocol, *allowAnon) 创建端口
ListPorts(ctx, tunnelID) 查询端口列表
ShowPort(ctx, tunnelID, port) 查询端口详情
UpdatePort(ctx, tunnelID, port, *allowAnon) 更新端口
DeletePort(ctx, tunnelID, port) 删除端口
Host / Connect
方法 说明
Host(ctx, HostConfig) 托管本地端口(阻塞)
Connect(ctx, ConnectConfig) 连接远端隧道(阻塞)

HostConfig / ConnectConfig 常用字段:

字段 说明
Ports 端口列表;Host 为空时从网关下发,Connect 为空时从 Host 通过 SSH 协商
JWTToken / APIKey 二选一,跳过 SDK 内部的令牌签发
LocalIP(仅 Connect) 本地监听地址,默认 127.0.0.1
OnReady 会话就绪回调:Host 返回托管端口列表,Connect 返回端口映射列表

错误处理

err := client.Host(ctx, cfg)
if err != nil {
	switch {
	case errors.Is(err, sdk.ErrMissingAPIKey):
		// 缺少 API Key
	case errors.Is(err, sdk.ErrTunnelNotFound):
		// 隧道不存在
	case errors.Is(err, sdk.ErrDuplicateHost):
		// 已有 Host 在运行
	case errors.Is(err, sdk.ErrQuotaExceeded):
		// 配额超限
	case errors.Is(err, sdk.ErrInvalidTunnelID):
		// 隧道 ID 格式无效
	case errors.Is(err, sdk.ErrInvalidTunnelDescription):
		// 隧道描述无效(仅中文/字母/数字,0-64 字符)
	case errors.Is(err, sdk.ErrInvalidPort):
		// 端口号无效
	default:
		// 其他错误
	}

	// 检查 API 业务错误
	if code, ok := sdk.IsAPIError(err); ok {
		fmt.Println("错误码:", code) // 如 "HD.98320078"
	}
}

架构

设备 A (Host)                          设备 B (Connect)
┌─────────────┐                       ┌──────────────┐
│ 本地服务     │                       │ 访问者       │
│ :8080       │                       │ localhost:8080│
└──────┬──────┘                       └──────┬───────┘
       │                                     │
  ┌────┴────┐                          ┌─────┴─────┐
  │ Host    │                          │ Connect   │
  │ (SDK)   │                          │ (SDK)     │
  └────┬────┘                          └─────┬─────┘
       │ WebSocket 出站                      │ WebSocket 出站
       └───────────┐     ┌──────────────────┘
                    ▼     ▼
               ┌─────────────────┐
               │ DevBridge 中继   │
               │ (SSH over WS)   │
               └─────────────────┘

Host 和 Connect 都主动连接 DevBridge 中继,因此 Host 所在设备不需要开放公网入站端口。

依赖

  • github.com/coder/websocket — WebSocket 客户端
  • github.com/microsoft/dev-tunnels-ssh — SSH 隧道协议

更新日志

见 CHANGELOG.md。

许可

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/open-api-inner/v1/relay-controller"
	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/17673651504/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.

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)
	}
}
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)
}
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)
	}
}
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)
	}
}
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)
}

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.

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.

Jump to

Keyboard shortcuts

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