> 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-es/kilo-center/kilo-mioty-service-center/integrations/api-reference/go-examples.md).

# Ejemplos en Go

Ejemplos ejecutables en Go para la API gRPC de KiloCenter — genera stubs con buf, autentica y llama a métodos de uplink.

Esta página proporciona ejemplos de Go ejecutables para la API gRPC de KiloCenter. Para la referencia completa de la API, consulte Referencia de la API.

Para documentación general de gRPC en Go, consulte [grpc.io/docs/languages/go](https://grpc.io/docs/languages/go/).

### Prerrequisitos

> Todos los comandos de esta guía asumen que su directorio de trabajo es `kilocenter-modules/`.

Genere stubs de Go a partir de las definiciones proto usando buf:

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

Esto produce código generado en `KC-Core/api/gen/kilocenter/v1/`.

Instale los módulos de Go requeridos:

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

### Obtener estado del sistema

Recupera el estado actual del sistema, incluida la versión, el tiempo de actividad y la salud de los servicios.

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

// el servidor es el endpoint gRPC de KiloCenter KC-Gateway.
var server = "localhost:9090"

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

	client := kilocenterv1.NewKiloCenterServiceClient(conn)

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

	fmt.Printf("Versión:            %s\n", resp.Version)
	fmt.Printf("Estado:             %s\n", resp.Status)
	fmt.Printf("Tiempo de actividad: %s\n", resp.Uptime.AsTime())
	fmt.Printf("Endpoints activos:   %d\n", resp.ActiveEndpoints)
	fmt.Printf("Estaciones base activas: %d\n", resp.ActiveBasestations)
	fmt.Printf("Mensajes procesados: %d\n", resp.MessagesProcessed)

	for _, svc := range resp.Services {
		fmt.Printf("  Servicio: %s  healthy=%v  latency=%dms\n", svc.Name, svc.Healthy, svc.LatencyMs)
	}
}
```

### Listar endpoints

Lista los endpoints registrados con compatibilidad para paginación. Perfil de alto volumen: tamaño de página predeterminado 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("error al 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 falló: %v", err)
		}

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

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

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

### Autenticación

#### Community Edition

Community Edition se ejecuta en modo de inquilino único con la autenticación y la aplicación de la organización deshabilitadas (`auth.enabled: false`, `org_enforcement_enabled: false`). Los ejemplos anteriores funcionan sin ningún encabezado.

#### Enterprise: principal de usuario JWT

Requiere tres encabezados: `authorization`, `x-organization-id`, y `x-user-id`. El `x-user-id` el valor debe coincidir con el usuario autenticado en el JWT. La ausencia de `x-user-id` devuelve `ErrTokenUserIDHeaderRequired`; una discrepancia devuelve `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: clave API de cuenta de servicio

Requiere dos encabezados: `authorization` y `x-organization-id`. No **no** envíe `x-user-id` — incluirlo devuelve `ErrTokenIdentityMismatch` para evitar la inyección de usuario.

```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 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.kiloiot.io/kilo-docs-es/kilo-center/kilo-mioty-service-center/integrations/api-reference/go-examples.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.
