Go SDK
零运行时依赖 —— 仅
net/http+encoding/json,250 行核心代码。
安装
go get github.com/gateway-new/sdk-go
初始化
import sdk "github.com/gateway-new/sdk-go"
c := sdk.New("https://api.gateway.wechas.com", "ak_xxx.yyy")
已封装的方法
| 方法 | HTTP | controls | 说明 |
|---|---|---|---|
ListHosts(ctx) | GET /v1/api/hosts | — | 列出本 API Key 所属的主机 |
MakeDir(ctx, hostId, DirRequest) | POST .../files/dir | 1 | 创建目录 |
RemoveDir(ctx, hostId, DirRequest) | POST .../files/dir | 2 | 删除目录 |
ExecShell(ctx, hostId, ShellRequest) | POST .../process/shell | 1<<13 | 同步 shell + stdout/stderr/exit_code |
ExecProgram(ctx, hostId, path, args) | POST .../process/exec | 1<<10 | 异步启动程序,返 pid |
KillProcess(ctx, hostId, name, timeoutS) | POST .../process/kill | 1<<12 | 软杀 → 超时硬杀 |
SystemMetrics(ctx, hostId) | POST .../system/metrics | 1<<25 | CPU/Mem/Disk/Net/TCP/Uptime |
RawControl(ctx, hostId, RawControlRequest) | POST .../controls/raw | 任意 | 直接下发 controls 值 |
错误处理
所有方法在非 2xx 时返回 *sdk.APIError,提供 helper:
err := c.ExecShell(ctx, hostID, req)
switch {
case sdk.IsInsufficientBalance(err):
// HTTP 402: 余额不足
case sdk.IsHostOffline(err):
// HTTP 409: host_offline
case err != nil:
// 其它错误(含网络、超时)
}
完整示例
package main
import (
"context"
"fmt"
"time"
sdk "github.com/gateway-new/sdk-go"
)
func main() {
c := sdk.New("https://api.gateway.wechas.com", "ak_xxx.yyy")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
hosts, _ := c.ListHosts(ctx)
for _, h := range hosts {
fmt.Printf("%s online=%v\n", h.Name, h.Online)
}
m, _ := c.SystemMetrics(ctx, hostID)
fmt.Printf("CPU=%.1f%% Mem=%.1f%% Disk=%.1f%%\n", m.CPUPct, m.MemPct, m.DiskPct)
r, err := c.ExecShell(ctx, hostID, sdk.ShellRequest{
Path: "powershell.exe",
Args: "Get-Process | Select-Object -First 5",
TimeoutS: 10,
})
if err != nil {
if sdk.IsInsufficientBalance(err) {
fmt.Println("余额不足")
return
}
panic(err)
}
fmt.Println(r.Stdout)
}
与其它 SDK 对应
Python SDK 与 TypeScript SDK 提供完全对齐的方法名(按各语言命名惯例)、参数顺序、错误类型。
源码
完整源码与单测见 sdk-clients/go/。