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

# Exemples Go

Exemples Go exécutables pour l’API gRPC de KiloCenter — générez des stubs avec buf, authentifiez-vous et appelez les méthodes de liaison montante.

Cette page fournit des exemples Go exécutables pour l’API gRPC KiloCenter. Pour la référence complète de l’API, voir Référence de l’API.

Pour la documentation générale sur gRPC en Go, voir [grpc.io/docs/languages/go](https://grpc.io/docs/languages/go/).

### Prérequis

> Toutes les commandes de ce guide supposent que votre répertoire de travail est `kilocenter-modules/`.

Générez les stubs Go à partir des définitions proto à l’aide de buf :

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

Cela génère du code dans `KC-Core/api/gen/kilocenter/v1/`.

Installez les modules Go requis :

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

### Obtenir l’état du système

Récupère l’état actuel du système, y compris la version, le temps de fonctionnement et l’état des services.

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

// le serveur est le point de terminaison gRPC KiloCenter KC-Gateway.
var server = "localhost:9090"

func main() {
	conn, err := grpc.NewClient(server, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("échec de la connexion : %v", err)
	}
	defer conn.Close()

	client := kilocenterv1.NewKiloCenterServiceClient(conn)

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

	fmt.Printf("Version:            %s\n", resp.Version)
	fmt.Printf("État:             %s\n", resp.Status)
	fmt.Printf("Durée de fonctionnement:             %s\n", resp.Uptime.AsTime())
	fmt.Printf("Points de terminaison actifs:   %d\n", resp.ActiveEndpoints)
	fmt.Printf("Stations de base actives: %d\n", resp.ActiveBasestations)
	fmt.Printf("Messages traités: %d\n", resp.MessagesProcessed)

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

### Lister les points de terminaison

Liste les points de terminaison enregistrés avec prise en charge de la pagination. Profil à volume élevé : taille de page par défaut 100, maximum 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("échec de la connexion : %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 a échoué : %v", err)
		}

		fmt.Printf("Nombre total de points de terminaison: %d\n", resp.TotalCount)

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

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

### Authentification

#### Édition communautaire

L’Édition communautaire fonctionne en mode mono-locataire avec l’authentification et l’application des organisations désactivées (`auth.enabled: false`, `org_enforcement_enabled: false`). Les exemples ci-dessus fonctionnent sans aucun en-tête.

#### Entreprise : principal utilisateur JWT

Nécessite trois en-têtes : `authorization`, `x-organization-id`, et `x-user-id`. Le `x-user-id` La valeur doit correspondre à l’utilisateur authentifié dans le JWT. L’absence de `x-user-id` renvoie `ErrTokenUserIDHeaderRequired`; une incompatibilité renvoie `ErrTokenIdentityMismatch`.

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

token := "votre-token-jwt"
orgID := "votre-uuid-d'organisation"
userID := "votre-uuid-utilisateur"

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

#### Entreprise : clé API de compte de service

Nécessite deux en-têtes : `authorization` et `x-organization-id`. Ne **pas** envoyez `x-user-id` — l’inclure renvoie `ErrTokenIdentityMismatch` pour empêcher l’injection d’utilisateur.

```go
apiKey := "votre-clé-api"
orgID := "votre-uuid-d'organisation"

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-fr/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.
