Go SDK [community]
SDK da Comunidade
Este SDK é totalmente mantido pela comunidade.
O Remnawave Go SDK é uma biblioteca para interação conveniente com a RestAPI.
✨ Principais Funcionalidades
- Gerado com ogen v1.19.0: Decodificador JSON sem reflexão para alto throughput
- Tipagem segura: Validação em tempo de compilação contra a especificação OpenAPI 3.0
- Design baseado em controladores: Sub-clientes organizados para acesso limpo à API
- Assinaturas simplificadas: Sem estruturas Params verbosas para operações simples
- Suporte a contexto: Suporte de primeira classe a
context.Context - OpenTelemetry: Instrumentação de rastreamento integrada
- Opções de requisição: Personalização por requisição via
...RequestOption - Editores: Suporte a middleware de requisição/resposta
Instalação
go get github.com/Jolymmiles/remnawave-api-go/v2@latest
aviso
Sempre escolha e fixe a versão correta do SDK para corresponder à versão do backend do Remnawave.
| Versão do SDK | Versão do Painel Remnawave |
|---|---|
| v2.6.1 | 2.6.1 |
| v2.5.3 | 2.5.3 |
| v2.3.0-6 | 2.3.0 |
| v2.2.6-3 | 2.2.6 |
Uso
Exemplo básico
package main
import (
"context"
"fmt"
"log"
remapi "github.com/Jolymmiles/remnawave-api-go/v2/api"
)
func main() {
ctx := context.Background()
// Create base client
baseClient, err := remapi.NewClient(
"https://your-panel.example.com",
remapi.StaticToken{Token: "YOUR_API_TOKEN"},
)
if err != nil {
log.Fatal(err)
}
// Wrap with organized sub-clients
client := remapi.NewClientExt(baseClient)
// Get user by UUID - simplified signature
resp, err := client.Users().GetUserByUuid(ctx, "user-uuid-here")
if err != nil {
log.Fatal(err)
}
switch r := resp.(type) {
case *remapi.UserResponse:
fmt.Printf("User: %s\n", r.Response.Username)
case *remapi.NotFoundError:
fmt.Println("User not found")
case *remapi.BadRequestError:
fmt.Printf("Validation error: %v\n", r.Errors)
}
}
Criar e gerenciar usuários
package main
import (
"context"
"fmt"
"log"
remapi "github.com/Jolymmiles/remnawave-api-go/v2/api"
)
func main() {
ctx := context.Background()
baseClient, _ := remapi.NewClient(
"https://your-panel.example.com",
remapi.StaticToken{Token: "YOUR_API_TOKEN"},
)
client := remapi.NewClientExt(baseClient)
// Create user
createResp, err := client.Users().CreateUser(ctx, &remapi.CreateUserRequest{
Username: "john_doe",
})
if err != nil {
log.Fatal(err)
}
user := createResp.(*remapi.UserResponse).Response
fmt.Printf("Created user: %s (UUID: %s)\n", user.Username, user.UUID)
// Disable user
_, err = client.Users().DisableUser(ctx, user.UUID.String())
if err != nil {
log.Fatal(err)
}
fmt.Println("User disabled")
// Enable user
_, err = client.Users().EnableUser(ctx, user.UUID.String())
if err != nil {
log.Fatal(err)
}
fmt.Println("User enabled")
// Delete user
_, err = client.Users().DeleteUser(ctx, user.UUID.String())
if err != nil {
log.Fatal(err)
}
fmt.Println("User deleted")
}
Gerenciamento de nós
package main
import (
"context"
"fmt"
"log"
remapi "github.com/Jolymmiles/remnawave-api-go/v2/api"
)
func main() {
ctx := context.Background()
baseClient, _ := remapi.NewClient(
"https://your-panel.example.com",
remapi.StaticToken{Token: "YOUR_API_TOKEN"},
)
client := remapi.NewClientExt(baseClient)
// Get all nodes
nodesResp, err := client.Nodes().GetAllNodes(ctx)
if err != nil {
log.Fatal(err)
}
nodes := nodesResp.(*remapi.NodesResponse).Response
fmt.Printf("Total nodes: %d\n", len(nodes))
for _, node := range nodes {
fmt.Printf(" - %s (%s): connected=%v\n",
node.Name, node.Address, node.IsConnected)
}
// Get single node
if len(nodes) > 0 {
nodeResp, _ := client.Nodes().GetOneNode(ctx, nodes[0].UUID.String())
node := nodeResp.(*remapi.NodeResponse).Response
fmt.Printf("\nNode details: %s\n", node.Name)
}
}
Paginação
package main
import (
"context"
"fmt"
"log"
remapi "github.com/Jolymmiles/remnawave-api-go/v2/api"
)
func main() {
ctx := context.Background()
baseClient, _ := remapi.NewClient(
"https://your-panel.example.com",
remapi.StaticToken{Token: "YOUR_API_TOKEN"},
)
client := remapi.NewClientExt(baseClient)
// Use PaginationHelper for iterating through pages
pager := remapi.NewPaginationHelper(50) // 50 items per page
for pager.HasMore {
resp, err := client.Users().GetAllUsers(ctx,
pager.Limit, // size
pager.Offset, // start
)
if err != nil {
log.Fatal(err)
}
users := resp.(*remapi.GetAllUsersResponse)
for _, user := range users.Response.Users {
fmt.Printf("User: %s (UUID: %s)\n", user.Username, user.UUID)
}
// Advance to next page
pager.SetTotal(int(users.Response.Total))
pager.NextPage()
}
fmt.Printf("Total users: %d\n", *pager.Total)
}
Tratamento de erros
package main
import (
"context"
"fmt"
"log"
remapi "github.com/Jolymmiles/remnawave-api-go/v2/api"
)
func main() {
ctx := context.Background()
baseClient, _ := remapi.NewClient(
"https://your-panel.example.com",
remapi.StaticToken{Token: "YOUR_API_TOKEN"},
)
client := remapi.NewClientExt(baseClient)
resp, err := client.Users().GetUserByUuid(ctx, "invalid-uuid")
if err != nil {
log.Fatal("Network error:", err)
}
// Available error types depend on the endpoint — check the generated
// Res interface (e.g. UsersGetUserByUuidRes) for the full list.
switch e := resp.(type) {
case *remapi.UserResponse:
fmt.Printf("User found: %s\n", e.Response.Username)
case *remapi.BadRequestError:
fmt.Println("Validation errors:")
for _, ve := range e.Errors {
fmt.Printf(" - %s: %s (path: %v)\n",
ve.Code, ve.Message, ve.Path)
}
case *remapi.NotFoundError:
fmt.Println("Resource not found")
case *remapi.InternalServerError:
fmt.Printf("Server error: %s\n", e.Message.Value)
}
}
Controladores Disponíveis
| Controlador | Descrição |
|---|---|
client.ApiTokens() | Gerenciamento de token de API |
client.Auth() | Autenticação |
client.BandwidthStatsNodes() | Estatísticas de largura de banda dos nós |
client.BandwidthStatsUsers() | Estatísticas de largura de banda dos usuários |
client.ConfigProfile() | Perfis de configuração |
client.ExternalSquad() | Esquadrões externos |
client.Hosts() | Gerenciamento de hosts |
client.HostsBulkActions() | Operações em lote de hosts |
client.HwidUserDevices() | Dispositivos HWID |
client.InfraBilling() | Cobrança de infraestrutura |
client.InternalSquad() | Esquadrões internos |
client.Keygen() | Geração de chaves |
client.Nodes() | Gerenciamento de nós |
client.NodesUsageHistory() | Histórico de uso dos nós |
client.Passkey() | Autenticação por passkey |
client.RemnawaveSettings() | Configurações do painel |
client.Snippets() | Snippets de código |
client.Subscription() | Gerenciamento de assinatura |
client.SubscriptionPageConfig() | Configuração da página de assinatura |
client.SubscriptionSettings() | Configurações de assinatura |
client.SubscriptionTemplate() | Modelos de assinatura |
client.Subscriptions() | Múltiplas assinaturas |
client.System() | Informações do sistema |
client.UserSubscriptionRequestHistory() | Histórico de requisições |
client.Users() | Gerenciamento de usuários |
client.UsersBulkActions() | Operações em lote de usuários |
Tipos de Erro
| Tipo | Status HTTP | Descrição |
|---|---|---|
BadRequestError | 400 | Erros de validação com detalhes |
UnauthorizedError | 401 | Autenticação necessária |
ForbiddenError | 403 | Acesso negado |
NotFoundError | 404 | Recurso não encontrado |
InternalServerError | 500 | Erro do servidor |
🛠️ Links do Projeto
- Repositório GitHub: remnawave-api-go no GitHub
- Autor: Jolymmiles