> For the complete documentation index, see [llms.txt](https://docs.verge.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.verge.io/automate-protect-and-extend/zh/ji-cheng-yu-api/go-sdk.md).

# VergeOS Go SDK（govergeos）

## 概述

govergeos 是一个用于通过 REST API 管理 VergeOS 基础设施的 Go 客户端库。它提供类型安全、符合 Go 习惯的接口，可用于自动化虚拟机生命周期、网络、存储、多租户操作和灾难恢复工作流，非常适合构建工具、控制器和基础设施自动化。

## 主要功能

* **虚拟机管理**：创建、配置、电源控制、克隆和快照
* **高级网络**：虚拟网络、防火墙规则、DHCP、DNS、IPSec VPN 和 WireGuard
* **NAS 与存储**: 卷管理、CIFS/NFS 共享、异步卷浏览和同步
* **多租户**: 具有资源隔离和节点管理的租户部署
* **灾难恢复**：云快照、站点同步和恢复工作流
* **类型安全 API**: 用于模拟、上下文支持和线程安全并发操作的完整 Go 接口
* **零依赖**: 仅使用标准库——无外部依赖
* **跨平台**：支持 Windows、macOS 和 Linux

## 要求

* Go 1.21 或更高版本
* VergeOS 26.0 或更高版本

## 安装

### 使用 go get

```bash
go get github.com/verge-io/govergeos
```

### 在 go.mod 中

```go
require github.com/verge-io/govergeos v0.1.2
```

## 身份验证

该 SDK 支持多种身份验证方式：

### 用户名/密码

```go
import vergeos "github.com/verge-io/govergeos"

client, err := vergeos.NewClient(
    vergeos.WithBaseURL("https://192.168.1.100"),
    vergeos.WithCredentials("admin", "secret"),
    vergeos.WithInsecureTLS(true), // 适用于自签名证书
)
if err != nil {
    log.Fatal(err)
}
```

{% hint style="info" %}
**SSL 证书验证**

设置 `WithInsecureTLS(true)` 仅适用于使用自签名证书的环境。对于具有有效证书的生产环境，请省略此选项。
{% endhint %}

### API 密钥

```go
client, err := vergeos.NewClient(
    vergeos.WithBaseURL("https://192.168.1.100"),
    vergeos.WithAPIKey("your-api-key-token"),
)
```

### 环境变量

```bash
export VERGEOS_HOST=https://192.168.1.100
export VERGEOS_USERNAME=admin
export VERGEOS_PASSWORD=secret
export VERGEOS_VERIFY_SSL=false
```

```go
client, err := vergeos.NewClient(vergeos.WithEnvConfig())
```

| 变量                   | 必需  | 默认值    | 描述                                        |
| -------------------- | --- | ------ | ----------------------------------------- |
| `VERGEOS_HOST`       | 是   | —      | 基础 URL（例如， `https://vergeos.example.com`) |
| `VERGEOS_USERNAME`   | 否\* | —      | 基础认证用户名                                   |
| `VERGEOS_PASSWORD`   | 否\* | —      | 基础认证密码                                    |
| `VERGEOS_API_KEY`    | 否\* | —      | 用于 Bearer 认证的 API 密钥                      |
| `VERGEOS_VERIFY_SSL` | 否   | `true` | 验证 TLS 证书                                 |
| `VERGEOS_TIMEOUT`    | 否   | `30`   | 请求超时（秒）                                   |

\*必须提供（USERNAME+PASSWORD）或 API\_KEY 之一。

{% hint style="success" %}
**生产环境推荐**

使用环境变量可避免在源代码中暴露凭据，并且便于在不同环境中使用不同凭据。
{% endhint %}

### 客户端选项

该客户端支持以下额外配置选项：

```go
client, err := vergeos.NewClient(
    vergeos.WithBaseURL("https://192.168.1.100"),
    vergeos.WithCredentials("admin", "secret"),
    vergeos.WithTimeout(60 * time.Second),
    vergeos.WithUserAgent("my-automation/1.0"),
    vergeos.WithHTTPClient(customHTTPClient),
)
```

## 可用资源

该 SDK 可访问以下 VergeOS 资源：

| 类别           | 服务                                                                                    |
| ------------ | ------------------------------------------------------------------------------------- |
| 虚拟机          | VMs, VMDrives, VMNICs, VMSnapshots, VMDevices                                         |
| 网络           | Networks, VNetRules, VNetAddresses, VNetHosts, VNetDNSViews/Zones/Records             |
| VPN          | VNetIPSecs, VNetIPSecPhase1s/Phase2s, VNetWireGuards, VNetWireGuardPeers              |
| NAS/存储       | NASServices, Volumes, VolumeSnapshots, VolumeCIFSShares, VolumeNFSShares, VolumeSyncs |
| 租户           | Tenants, TenantNodes, TenantStorage, TenantSnapshots, TenantLayer2Networks            |
| 用户和组         | Users, Groups, Members, Permissions, UserAPIKeys                                      |
| 系统           | Clusters, Nodes, Settings, System, Certificates                                       |
| 监控           | Alarms, Logs, Tasks, StorageTiers, ClusterTiers                                       |
| 备份与灾难恢复      | SnapshotProfiles, CloudSnapshots, Sites, SiteSyncs                                    |
| 自动化          | Files, CloudInitFiles, WebhookURLs, Webhooks                                          |
| Organization | Tags, TagCategories, TagMembers, ResourceGroups                                       |

## 使用示例

### 管理虚拟机

```go
import (
    "context"
    "fmt"
    "log"

    vergeos "github.com/verge-io/govergeos"
)

func main() {
    client, err := vergeos.NewClient(
        vergeos.WithBaseURL("https://192.168.1.100"),
        vergeos.WithCredentials("admin", "secret"),
        vergeos.WithInsecureTLS(true),
    )
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    // 列出所有虚拟机
    vms, err := client.VMs.List(ctx)
    if err != nil {
        log.Fatal(err)
    }
    for _, vm := range vms {
        fmt.Printf("%s: %dMB RAM, %d cores\n", vm.Name, vm.RAM, vm.CPUCores)
    }

    // 获取指定虚拟机
    vm, err := client.VMs.Get(ctx, 42)
    if err != nil {
        log.Fatal(err)
    }

    // 创建虚拟机
    newVM, err := client.VMs.Create(ctx, &vergeos.VMCreateRequest{
        Name:     "test-vm",
        RAM:      2048,
        CPUCores: 2,
        Cluster:  1,
    })
    if err != nil {
        log.Fatal(err)
    }

    // 电源操作（使用 ID.Int() 获取整数 ID）
    _ = client.VMs.PowerOn(ctx, newVM.ID.Int())
    _ = client.VMs.PowerOff(ctx, newVM.ID.Int())
    _ = client.VMs.Reset(ctx, newVM.ID.Int())

    // 创建快照
    _ = client.VMs.Snapshot(ctx, newVM.ID.Int(), &vergeos.VMSnapshotOptions{
        Name: "pre-upgrade",
    })

    // 克隆虚拟机
    clone, _ := client.VMs.Clone(ctx, vm.ID.Int(), &vergeos.VMCloneOptions{
        Name: "test-clone",
    })
    fmt.Printf("已克隆的虚拟机：%s\n", clone.Name)
}
```

### 创建和管理网络

```go
ctx := context.Background()

// 创建虚拟网络
network, err := client.Networks.Create(ctx, &vergeos.NetworkCreateRequest{
    Name:        "app-network",
    Network:     "10.10.1.0/24",
    IPAddress:   "10.10.1.1",
    DHCPEnabled: vergeos.Ptr(true),
    DHCPStart:   "10.10.1.100",
    DHCPStop:    "10.10.1.200",
})
if err != nil {
    log.Fatal(err)
}

// 启动网络
_ = client.Networks.PowerOn(ctx, network.ID.Int())

// 添加防火墙规则
rule, err := client.VNetRules.Create(ctx, &vergeos.VNetRuleCreateRequest{
    VNet:             network.ID.Int(),
    Name:             "允许 SSH",
    Action:           vergeos.Ptr("accept"),
    Protocol:         vergeos.Ptr("tcp"),
    Direction:        vergeos.Ptr("incoming"),
    DestinationPorts: vergeos.Ptr("22"),
})
if err != nil {
    log.Fatal(err)
}

// 应用规则
_ = client.Networks.ApplyRules(ctx, network.ID.Int())
```

### 过滤资源

该 SDK 支持使用列表选项进行灵活筛选：

{% tabs %}
{% tab title="基本筛选" %}

```go
// 按电源状态筛选虚拟机（运行中）
vms, err := client.VMs.List(ctx,
    vergeos.WithFilter("powerstate eq true"),
)
```

{% endtab %}

{% tab title="多个选项" %}

```go
// 组合筛选、排序和分页
vms, err := client.VMs.List(ctx,
    vergeos.WithFilter("os_family eq 'linux' and ram gt 2048"),
    vergeos.WithSort("name"),
    vergeos.WithLimit(10),
    vergeos.WithOffset(0),
)
```

{% endtab %}

{% tab title="字段选择" %}

```go
// 仅返回特定字段（ID 字段使用 $key）
vms, err := client.VMs.List(ctx,
    vergeos.WithFields("$key,name,powerstate,ram"),
)
```

{% endtab %}
{% endtabs %}

### 并发操作

该 SDK 线程安全，并支持使用 goroutine 进行并发操作：

```go
import "sync"

var wg sync.WaitGroup
vmIDs := []int{1, 2, 3, 4, 5}

for _, id := range vmIDs {
    wg.Add(1)
    go func(vmID int) {
        defer wg.Done()
        vm, err := client.VMs.Get(ctx, vmID)
        if err != nil {
            log.Printf("获取虚拟机 %d 时出错：%v", vmID, err)
            return
        }
        status := "已停止"
        if vm.PowerState {
            status = "运行中"
        }
        fmt.Printf("虚拟机：%s，电源状态：%s\n", vm.Name, status)
    }(id)
}
wg.Wait()
```

{% hint style="success" %}
**上下文取消**

所有方法都接受一个 `context.Context`，以便为长时间运行的操作设置超时并处理取消。
{% endhint %}

## 错误处理

该 SDK 为不同错误情况提供了特定错误类型：

```go
import vergeos "github.com/verge-io/govergeos"

vm, err := client.VMs.Get(ctx, 999)
if err != nil {
    if vergeos.IsNotFoundError(err) {
        fmt.Println("未找到虚拟机")
    } else if vergeos.IsAuthError(err) {
        fmt.Println("认证失败")
    } else if vergeos.IsValidationError(err) {
        fmt.Println("无效的请求参数")
    } else {
        fmt.Printf("意外错误：%v\n", err)
    }
}
```

{% hint style="info" %}
**可用的错误类型**
{% endhint %}

| 错误类型                      | 辅助函数                             | 描述              |
| ------------------------- | -------------------------------- | --------------- |
| `APIError`                | —                                | 所有 API 错误的基础错误  |
| `AuthError`               | `IsAuthError(err)`               | 凭据无效或令牌已过期      |
| `NotFoundError`           | `IsNotFoundError(err)`           | 请求的资源不存在        |
| `ValidationError`         | `IsValidationError(err)`         | 参数值无效           |
| `UnsupportedVersionError` | `IsUnsupportedVersionError(err)` | 不支持的 VergeOS 版本 |

## 常见用例

* **基础设施自动化**：以编程方式预配虚拟机、网络和存储
* **Kubernetes 操作器**: 为 VergeOS 资源构建自定义控制器
* **CI/CD 集成**：在流水线中创建和销毁测试环境
* **监控工具**: 查询资源状态并构建自定义仪表板
* **备份自动化**：安排并管理快照和云备份
* **多租户预配**：自动化租户创建和资源分配

## 文档和资源

完整文档（包括所有可用方法和详细使用示例）请访问官方仓库：

* [GitHub 仓库](https://github.com/verge-io/govergeos)
* [Go 包文档](https://pkg.go.dev/github.com/verge-io/govergeos)

## 支持

如果您遇到问题或有功能请求，请在 GitHub 仓库中提交 issue：

<https://github.com/verge-io/govergeos/issues>

## 其他资源

* [Go 文档](https://go.dev/doc/)
* [VergeOS API 文档](/knowledge-base/zh/automation-api/verge-api-guide.md)
* [Python SDK（pyvergeos）](/automate-protect-and-extend/zh/ji-cheng-yu-api/python-sdk.md) - Python 替代方案
* [Terraform 提供程序](/automate-protect-and-extend/zh/ji-cheng-yu-api/terraform-provider.md) - 基础设施即代码


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.verge.io/automate-protect-and-extend/zh/ji-cheng-yu-api/go-sdk.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
