> For the complete documentation index, see [llms.txt](https://docs.kiloiot.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kiloiot.io/kilo-docs-pt/kilo-center/kilo-mioty-service-center/integrations/api-reference/go-examples.md).

# Exemplos em Go

Exemplos executáveis em Go para a API gRPC do KiloCenter — gere stubs com buf, autentique e chame métodos de uplink.

Esta página fornece exemplos executáveis em Go para a API gRPC do KiloCenter. Para a referência completa da API, consulte a Referência da API.

Para documentação geral do gRPC em Go, veja [grpc.io/docs/languages/go](https://grpc.io/docs/languages/go/).

### Pré-requisitos

> Todos os comandos neste guia pressupõem que o seu diretório de trabalho é `kilocenter-modules/`.

Gere stubs Go a partir das definições proto usando o buf:

```bash
cd KC-Core/api/proto && buf generate
```

Isto produz código gerado em `KC-Core/api/gen/kilocenter/v1/`.

Instale os módulos Go necessários:

```bash
go get google.golang.org/grpc
go get google.golang.org/protobuf
```

### Obter estado do sistema

Recupera o estado atual do sistema, incluindo versão, tempo de atividade e saúde do serviço.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/protobuf/types/known/emptypb"

	kilocenterv1 "github.com/kilocenter/KC-Core/api/gen/kilocenter/v1"
)

// o servidor é o endpoint gRPC KiloCenter KC-Gateway.
var server = "localhost:9090"

func main() {
	conn, err := grpc.NewClient(server, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("falha ao conectar: %v", err)
	}
	defer conn.Close()

	client := kilocenterv1.NewKiloCenterServiceClient(conn)

	resp, err := client.GetSystemStatus(context.Background(), &emptypb.Empty{})
	if err != nil {
		log.Fatalf("GetSystemStatus falhou: %v", err)
	}

	fmt.Printf("Versão:            %s\n", resp.Version)
	fmt.Printf("Estado:            %s\n", resp.Status)
	fmt.Printf("Tempo de atividade: %s\n", resp.Uptime.AsTime())
	fmt.Printf("Pontos de extremidade ativos:   %d\n", resp.ActiveEndpoints)
	fmt.Printf("Estações-base ativas: %d\n", resp.ActiveBasestations)
	fmt.Printf("Mensagens processadas: %d\n", resp.MessagesProcessed)

	for _, svc := range resp.Services {
		fmt.Printf("  Serviço: %s  saudável=%v  latência=%dms\n", svc.Name, svc.Healthy, svc.LatencyMs)
	}
}
```

### Listar pontos de extremidade

Lista os pontos de extremidade registados com suporte a paginação. Perfil de alto volume: tamanho padrão da página 100, máximo 1000.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	kilocenterv1 "github.com/kilocenter/KC-Core/api/gen/kilocenter/v1"
)

var server = "localhost:9090"

func main() {
	conn, err := grpc.NewClient(server, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("falha ao conectar: %v", err)
	}
	defer conn.Close()

	client := kilocenterv1.NewKiloCenterServiceClient(conn)

	pageToken := ""
	pageSize := int32(100)

	for {
		resp, err := client.ListEndPoints(context.Background(), &kilocenterv1.ListEndPointsRequest{
			PageSize:  pageSize,
			PageToken: pageToken,
		})
		if err != nil {
			log.Fatalf("ListEndPoints falhou: %v", err)
		}

		fmt.Printf("Total de pontos de extremidade: %d\n", resp.TotalCount)

		for _, ep := range resp.Endpoints {
			fmt.Printf("  EUI: %s  Nome: %s  Estado: %s  Classe: %s\n",
				ep.EpEui, ep.Name, ep.Status, ep.EpClass)
		}

		if resp.NextPageToken == "" {
			break
		}
		pageToken = resp.NextPageToken
	}
}
```

### Autenticação

#### Edição Comunitária

A Edição Comunitária é executada em modo de inquilino único com autenticação e imposição de organização desativadas (`auth.enabled: false`, `org_enforcement_enabled: false`). Os exemplos acima funcionam sem quaisquer cabeçalhos.

#### Enterprise: Principal do utilizador JWT

Requer três cabeçalhos: `authorization`, `x-organization-id` e `x-user-id`. O `x-user-id` o valor deve corresponder ao utilizador autenticado no JWT. Em falta `x-user-id` retorna `ErrTokenUserIDHeaderRequired`; uma incompatibilidade retorna `ErrTokenIdentityMismatch`.

```go
import "google.golang.org/grpc/metadata"

token := "your-jwt-token"
orgID := "your-organization-uuid"
userID := "your-user-uuid"

ctx := metadata.AppendToOutgoingContext(context.Background(),
	"authorization", "Bearer "+token,
	"x-organization-id", orgID,
	"x-user-id", userID,
)

resp, err := client.ListEndPoints(ctx, &kilocenterv1.ListEndPointsRequest{
	PageSize: 100,
})
```

#### Enterprise: Chave de API da conta de serviço

Requer dois cabeçalhos: `authorization` e `x-organization-id`. Não **não** enviar `x-user-id` — incluindo-o retorna `ErrTokenIdentityMismatch` para impedir injeção de utilizador.

```go
apiKey := "your-api-key"
orgID := "your-organization-uuid"

ctx := metadata.AppendToOutgoingContext(context.Background(),
	"authorization", "Bearer "+apiKey,
	"x-organization-id", orgID,
)

resp, err := client.ListEndPoints(ctx, &kilocenterv1.ListEndPointsRequest{
	PageSize: 100,
})
```


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.kiloiot.io/kilo-docs-pt/kilo-center/kilo-mioty-service-center/integrations/api-reference/go-examples.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
