package main
import (
"context"
"fmt"
"log"
"os"
"github.com/elastic/go-elasticsearch/v8"
)
func main() {
// Get Elasticsearch configuration from environment variables
esURI := os.Getenv("ELASTICSEARCH_URI")
esUsername := os.Getenv("ELASTICSEARCH_USERNAME")
esPassword := os.Getenv("ELASTICSEARCH_PASSWORD")
if esURI == "" || esUsername == "" || esPassword == "" {
log.Fatal("Environment variables ELASTICSEARCH_URI, ELASTICSEARCH_USERNAME, and ELASTICSEARCH_PASSWORD must be set")
}
// Define the Elasticsearch connection configuration
esConfig := elasticsearch.Config{
Addresses: []string{
esURI,
},
Username: esUsername,
Password: esPassword,
}
// Create a new Elasticsearch client
es, err := elasticsearch.NewClient(esConfig)
if err != nil {
log.Fatalf("Error creating the Elasticsearch client: %s", err)
}
// Test the connection
res, err := es.Info()
if err != nil {
log.Fatalf("Error getting Elasticsearch info: %s", err)
}
defer res.Body.Close()
// Print the response
if res.IsError() {
log.Fatalf("Elasticsearch returned an error: %s", res.String())
}
fmt.Println("Connected to Elasticsearch successfully!")
fmt.Println(res.String())
}