> 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/vi/tich-hop-va-api/go-sdk.md).

# VergeOS Go SDK (govergeos)

## Tổng quan

govergeos là một thư viện client Go để quản lý hạ tầng VergeOS thông qua REST API. Nó cung cấp một giao diện Go an toàn kiểu, đúng phong cách Go để tự động hóa vòng đời VM, mạng, lưu trữ, thao tác đa tenant và quy trình phục hồi sau thảm họa, rất phù hợp để xây dựng công cụ, operator và tự động hóa hạ tầng.

## Tính năng chính

* **Quản lý VM**: Tạo, cấu hình, điều khiển nguồn, sao chép và snapshot
* **Mạng nâng cao**: Mạng ảo, quy tắc tường lửa, DHCP, DNS, VPN IPSec và WireGuard
* **NAS & Lưu trữ**: Quản lý volume, chia sẻ CIFS/NFS, duyệt volume không đồng bộ và đồng bộ hóa
* **Đa thuê bao**: Cấp phát tenant với cô lập tài nguyên và quản lý node
* **Khôi phục sau thảm họa**: Snapshot đám mây, đồng bộ hóa site và quy trình khôi phục
* **API an toàn kiểu**: Các interface Go đầy đủ để mock, hỗ trợ context và các thao tác đồng thời an toàn với luồng
* **Không phụ thuộc**: Chỉ dùng thư viện chuẩn—không có phụ thuộc bên ngoài
* **Đa nền tảng**: Hỗ trợ Windows, macOS và Linux

## Yêu cầu

* Go 1.21 trở lên
* VergeOS 26.0 trở lên

## Cài đặt

### Dùng go get

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

### Trong go.mod

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

## Xác thực

SDK hỗ trợ nhiều phương thức xác thực:

### Tên người dùng/Mật khẩu

```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), // Dành cho chứng chỉ tự ký
)
if err != nil {
    log.Fatal(err)
}
```

{% hint style="info" %}
**Xác minh chứng chỉ SSL**

Đặt `WithInsecureTLS(true)` chỉ dành cho môi trường có chứng chỉ tự ký. Với môi trường sản xuất có chứng chỉ hợp lệ, hãy bỏ qua tùy chọn này.
{% endhint %}

### Khóa API

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

### Biến môi trường

```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())
```

| Biến                 | Bắt buộc | Mặc định | Mô tả                                            |
| -------------------- | -------- | -------- | ------------------------------------------------ |
| `VERGEOS_HOST`       | Có       | —        | URL cơ sở (ví dụ, `https://vergeos.example.com`) |
| `VERGEOS_USERNAME`   | Không\*  | —        | Tên người dùng cho xác thực cơ bản               |
| `VERGEOS_PASSWORD`   | Không\*  | —        | Mật khẩu cho xác thực cơ bản                     |
| `VERGEOS_API_KEY`    | Không\*  | —        | Khóa API để xác thực bearer                      |
| `VERGEOS_VERIFY_SSL` | Không    | `true`   | Xác minh chứng chỉ TLS                           |
| `VERGEOS_TIMEOUT`    | Không    | `30`     | Thời gian chờ yêu cầu tính bằng giây             |

\*Cần một trong hai: (USERNAME+PASSWORD) hoặc API\_KEY.

{% hint style="success" %}
**Khuyến nghị cho môi trường sản xuất**

Sử dụng biến môi trường giúp giữ thông tin xác thực ra khỏi mã nguồn của bạn và dễ dàng dùng các thông tin xác thực khác nhau giữa các môi trường.
{% endhint %}

### Tùy chọn client

Client hỗ trợ các tùy chọn cấu hình bổ sung:

```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),
)
```

## Tài nguyên có sẵn

SDK cung cấp quyền truy cập vào các tài nguyên VergeOS sau:

| Danh mục          | Dịch vụ                                                                               |
| ----------------- | ------------------------------------------------------------------------------------- |
| Máy ảo            | VMs, VMDrives, VMNICs, VMSnapshots, VMDevices                                         |
| Mạng              | Networks, VNetRules, VNetAddresses, VNetHosts, VNetDNSViews/Zones/Records             |
| VPN               | VNetIPSecs, VNetIPSecPhase1s/Phase2s, VNetWireGuards, VNetWireGuardPeers              |
| NAS/Lưu trữ       | NASServices, Volumes, VolumeSnapshots, VolumeCIFSShares, VolumeNFSShares, VolumeSyncs |
| Tenant            | Tenants, TenantNodes, TenantStorage, TenantSnapshots, TenantLayer2Networks            |
| Người dùng & Nhóm | Users, Groups, Members, Permissions, UserAPIKeys                                      |
| Hệ thống          | Clusters, Nodes, Settings, System, Certificates                                       |
| Giám sát          | Alarms, Logs, Tasks, StorageTiers, ClusterTiers                                       |
| Sao lưu & DR      | SnapshotProfiles, CloudSnapshots, Sites, SiteSyncs                                    |
| Tự động hóa       | Files, CloudInitFiles, WebhookURLs, Webhooks                                          |
| Organization      | Tags, TagCategories, TagMembers, ResourceGroups                                       |

## Ví dụ sử dụng

### Quản lý máy ảo

```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()

    // Liệt kê tất cả VM
    vms, err := client.VMs.List(ctx)
    if err != nil {
        log.Fatal(err)
    }
    for _, vm := range vms {
        fmt.Printf("%s: %dMB RAM, %d lõi\n", vm.Name, vm.RAM, vm.CPUCores)
    }

    // Lấy một VM cụ thể
    vm, err := client.VMs.Get(ctx, 42)
    if err != nil {
        log.Fatal(err)
    }

    // Tạo một VM
    newVM, err := client.VMs.Create(ctx, &vergeos.VMCreateRequest{
        Name:     "test-vm",
        RAM:      2048,
        CPUCores: 2,
        Cluster:  1,
    })
    if err != nil {
        log.Fatal(err)
    }

    // Các thao tác nguồn (dùng ID.Int() để lấy ID số nguyên)
    _ = client.VMs.PowerOn(ctx, newVM.ID.Int())
    _ = client.VMs.PowerOff(ctx, newVM.ID.Int())
    _ = client.VMs.Reset(ctx, newVM.ID.Int())

    // Tạo snapshot
    _ = client.VMs.Snapshot(ctx, newVM.ID.Int(), &vergeos.VMSnapshotOptions{
        Name: "pre-upgrade",
    })

    // Nhân bản một VM
    clone, _ := client.VMs.Clone(ctx, vm.ID.Int(), &vergeos.VMCloneOptions{
        Name: "test-clone",
    })
    fmt.Printf("VM đã nhân bản: %s\n", clone.Name)
}
```

### Tạo và quản lý mạng

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

// Tạo mạng ảo
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)
}

// Bật nguồn cho mạng
_ = client.Networks.PowerOn(ctx, network.ID.Int())

// Thêm quy tắc tường lửa
rule, err := client.VNetRules.Create(ctx, &vergeos.VNetRuleCreateRequest{
    VNet:             network.ID.Int(),
    Name:             "Allow SSH",
    Action:           vergeos.Ptr("accept"),
    Protocol:         vergeos.Ptr("tcp"),
    Direction:        vergeos.Ptr("incoming"),
    DestinationPorts: vergeos.Ptr("22"),
})
if err != nil {
    log.Fatal(err)
}

// Áp dụng các quy tắc
_ = client.Networks.ApplyRules(ctx, network.ID.Int())
```

### Lọc tài nguyên

SDK hỗ trợ lọc linh hoạt với các tùy chọn danh sách:

{% tabs %}
{% tab title="Lọc cơ bản" %}

```go
// Lọc VM theo trạng thái nguồn (đang chạy)
vms, err := client.VMs.List(ctx,
    vergeos.WithFilter("powerstate eq true"),
)
```

{% endtab %}

{% tab title="Nhiều tùy chọn" %}

```go
// Kết hợp lọc, sắp xếp và phân trang
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="Chọn trường" %}

```go
// Chỉ trả về các trường cụ thể (dùng $key cho trường ID)
vms, err := client.VMs.List(ctx,
    vergeos.WithFields("$key,name,powerstate,ram"),
)
```

{% endtab %}
{% endtabs %}

### Thao tác đồng thời

SDK an toàn với luồng và hỗ trợ các thao tác đồng thời bằng 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("Lỗi khi lấy VM %d: %v", vmID, err)
            return
        }
        status := "stopped"
        if vm.PowerState {
            status = "running"
        }
        fmt.Printf("VM: %s, Trạng thái nguồn: %s\n", vm.Name, status)
    }(id)
}
wg.Wait()
```

{% hint style="success" %}
**Hủy context**

Tất cả các phương thức chấp nhận một `context.Context`, cho phép bạn đặt thời gian chờ và xử lý việc hủy cho các thao tác chạy lâu.
{% endhint %}

## Xử lý lỗi

SDK cung cấp các kiểu lỗi cụ thể cho các điều kiện lỗi khác nhau:

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

vm, err := client.VMs.Get(ctx, 999)
if err != nil {
    if vergeos.IsNotFoundError(err) {
        fmt.Println("Không tìm thấy VM")
    } else if vergeos.IsAuthError(err) {
        fmt.Println("Xác thực thất bại")
    } else if vergeos.IsValidationError(err) {
        fmt.Println("Tham số yêu cầu không hợp lệ")
    } else {
        fmt.Printf("Lỗi không mong đợi: %v\n", err)
    }
}
```

{% hint style="info" %}
**Các kiểu lỗi có sẵn**
{% endhint %}

| Kiểu lỗi                  | Hàm trợ giúp                     | Mô tả                                                 |
| ------------------------- | -------------------------------- | ----------------------------------------------------- |
| `APIError`                | —                                | Lỗi cơ sở cho mọi lỗi API                             |
| `AuthError`               | `IsAuthError(err)`               | Thông tin xác thực không hợp lệ hoặc token đã hết hạn |
| `NotFoundError`           | `IsNotFoundError(err)`           | Tài nguyên được yêu cầu không tồn tại                 |
| `ValidationError`         | `IsValidationError(err)`         | Giá trị tham số không hợp lệ                          |
| `UnsupportedVersionError` | `IsUnsupportedVersionError(err)` | Phiên bản VergeOS không được hỗ trợ                   |

## Các trường hợp sử dụng phổ biến

* **Tự động hóa hạ tầng**: Cấp phát VM, mạng và lưu trữ bằng chương trình
* **Các operator Kubernetes**: Xây dựng các controller tùy chỉnh cho tài nguyên VergeOS
* **Tích hợp CI/CD**: Tạo và hủy môi trường thử nghiệm trong pipeline
* **Công cụ giám sát**: Truy vấn trạng thái tài nguyên và xây dựng dashboard tùy chỉnh
* **Tự động hóa sao lưu**: Lên lịch và quản lý snapshot cùng bản sao lưu đám mây
* **Cấp phát đa thuê bao**: Tự động hóa việc tạo tenant và phân bổ tài nguyên

## Tài liệu và tài nguyên

Để có tài liệu đầy đủ, bao gồm tất cả các phương thức có sẵn và ví dụ sử dụng chi tiết, hãy truy cập kho lưu trữ chính thức:

* [Kho lưu trữ GitHub](https://github.com/verge-io/govergeos)
* [Tài liệu gói Go](https://pkg.go.dev/github.com/verge-io/govergeos)

## Hỗ trợ

Nếu bạn gặp sự cố hoặc có yêu cầu tính năng, vui lòng mở một issue trên kho lưu trữ GitHub:

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

## Tài nguyên bổ sung

* [Tài liệu Go](https://go.dev/doc/)
* [Tài liệu API VergeOS](/knowledge-base/vi/automation-api/verge-api-guide.md)
* [SDK Python (pyvergeos)](/automate-protect-and-extend/vi/tich-hop-va-api/python-sdk.md) - Phương án thay thế Python
* [Nhà cung cấp Terraform](/automate-protect-and-extend/vi/tich-hop-va-api/terraform-provider.md) - Hạ tầng dưới dạng mã


---

# 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/vi/tich-hop-va-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.
