Skip to content

Instantly share code, notes, and snippets.

@robsears
Last active July 26, 2018 19:32
Show Gist options
  • Save robsears/807f1b3b73f37300d60a909265e5ccd6 to your computer and use it in GitHub Desktop.
Save robsears/807f1b3b73f37300d60a909265e5ccd6 to your computer and use it in GitHub Desktop.
// Demo for connecting to Bonsai.io using the Elasticsearch client for Go.
// Make sure to match your Bonsai cluster version to the Go client version.
// Validated using a Bonsai cluster running Elasticsearch 6.2.3.
//
// 1. go get github.com/olivere/elastic
// 2. go build bonsai.go
// 3. ./bonsai
// 4. Program will create an index called `test` on your Bonsai cluster.
//
// Feel free to tweak/clean up as needed, golang isn't my specialty.
package main
import(
"github.com/olivere/elastic"
"os"
"regexp"
"strings"
"context"
)
func main() {
// Get the host, username and password for a cluster from the environment
user,pass,host := parseBonsaiURL()
// Set up a simple client
client, err := elastic.NewSimpleClient(
elastic.SetURL(host),
elastic.SetBasicAuth(user, pass),
elastic.SetMaxRetries(10),
elastic.SetSniff(false),
elastic.SetHealthcheck(false))
if err != nil {
panic(err)
}
// Create a test index to prove the client can connect to Bonsai
_, err = client.CreateIndex("test").Do(context.Background())
if err != nil {
panic(err)
}
}
// Bonsai URLs have a randomized username and password like so:
// https://a1b2c3d4e5:f6g7h8i9j0@some-host-12345.us-east-1.bonsaisearch.net
// Often this is stored in an environment variable, usually called `BONSAI_URL`
// This function reads the environment variable and extracts the host, username
// and password for the cluster.
func parseBonsaiURL() (string, string, string) {
url := os.Getenv("BONSAI_URL")
rex, _ := regexp.Compile(".*?://([a-z0-9]{1,}):([a-z0-9]{1,})@.*$")
user := rex.ReplaceAllString(url, "$1")
pass := rex.ReplaceAllString(url, "$2")
host := strings.Replace(url, user+":"+pass+"@", "", -1)
return user,pass,host
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment