Service examples for Go

Memcached Sample Code

Source

package examples

import (
	"fmt"
	"github.com/bradfitz/gomemcache/memcache"
	psh "github.com/platformsh/config-reader-go/v2"
	gomemcache "github.com/platformsh/config-reader-go/v2/gomemcache"
)

func UsageExampleMemcached() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// Get the credentials to connect to the Solr service.
	credentials, err := config.Credentials("memcached")
	checkErr(err)

	// Retrieve formatted credentials for gomemcache.
	formatted, err := gomemcache.FormattedCredentials(credentials)
	checkErr(err)

	// Connect to Memcached.
	mc := memcache.New(formatted)

	// Set a value.
	key := "Deploy_day"
	value := "Friday"

	err = mc.Set(&memcache.Item{Key: key, Value: []byte(value)})

	// Read it back.
	test, err := mc.Get(key)

	return fmt.Sprintf("Found value <strong>%s</strong> for key <strong>%s</strong>.", test.Value, key)
}

Output

Found value Friday for key Deploy_day.
MongoDB Sample Code

Source

package examples

import (
	"context"
	"fmt"
	psh "github.com/platformsh/config-reader-go/v2"
	mongoPsh "github.com/platformsh/config-reader-go/v2/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

func UsageExampleMongoDB() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// Get the credentials to connect to the Solr service.
	credentials, err := config.Credentials("mongodb")
	checkErr(err)

	// Retrieve the formatted credentials for mongo-driver.
	formatted, err := mongoPsh.FormattedCredentials(credentials)
	checkErr(err)

	// Connect to MongoDB using the formatted credentials.
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(formatted))
	checkErr(err)

	// Create a new collection.
	collection := client.Database("main").Collection("starwars")

	// Clean up after ourselves.
	err = collection.Drop(context.Background())
	checkErr(err)

	// Create an entry.
	res, err := collection.InsertOne(ctx, bson.M{"name": "Rey", "occupation": "Jedi"})
	checkErr(err)

	id := res.InsertedID

	// Read it back.
	cursor, err := collection.Find(context.Background(), bson.M{"_id": id})
	checkErr(err)

	var name string
	var occupation string

	for cursor.Next(context.Background()) {
		document := struct {
			Name       string
			Occupation string
		}{}
		err := cursor.Decode(&document)
		checkErr(err)

		name = document.Name
		occupation = document.Occupation
	}

	return fmt.Sprintf("Found %s (%s)", name, occupation)
}

Output

Found Rey (Jedi)
MySQL Sample Code

Source

package examples

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	psh "github.com/platformsh/config-reader-go/v2"
	sqldsn "github.com/platformsh/config-reader-go/v2/sqldsn"
)

func UsageExampleMySQL() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// The 'database' relationship is generally the name of the primary SQL database of an application.
	// That's not required, but much of our default automation code assumes it.
	credentials, err := config.Credentials("database")
	checkErr(err)

	// Using the sqldsn formatted credentials package.
	formatted, err := sqldsn.FormattedCredentials(credentials)
	checkErr(err)

	db, err := sql.Open("mysql", formatted)
	checkErr(err)

	defer db.Close()

	// Force MySQL into modern mode.
	db.Exec("SET NAMES=utf8")
	db.Exec("SET sql_mode = 'ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES," +
		"NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO," +
		"NO_AUTO_CREATE_USER,ONLY_FULL_GROUP_BY'")

	// Creating a table.
	sqlCreate := "CREATE TABLE IF NOT EXISTS People (" +
		"id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY," +
		"name VARCHAR(30) NOT NULL," +
		"city VARCHAR(30) NOT NULL)"

	_, err = db.Exec(sqlCreate)
	checkErr(err)

	// Insert data.
	sqlInsert := "INSERT INTO People (name, city) VALUES" +
		"('Neil Armstrong', 'Moon')," +
		"('Buzz Aldrin', 'Glen Ridge')," +
		"('Sally Ride', 'La Jolla');"

	_, err = db.Exec(sqlInsert)
	checkErr(err)

	table := "<table>" +
		"<thead>" +
		"<tr><th>Name</th><th>City</th></tr>" +
		"</thead>" +
		"<tbody>"

	var id int
	var name string
	var city string

	rows, err := db.Query("SELECT * FROM People")
	if err != nil {
		panic(err)
	} else {
		for rows.Next() {
			err = rows.Scan(&id, &name, &city)
			checkErr(err)
			table += fmt.Sprintf("<tr><td>%s</td><td>%s</td><tr>\n", name, city)
		}
		table += "</tbody>\n</table>\n"
	}

	_, err = db.Exec("DROP TABLE People;")
	checkErr(err)

	return table
}

Output

NameCity
Neil ArmstrongMoon
Buzz AldrinGlen Ridge
Sally RideLa Jolla
PostgreSQL Sample Code

Source

package examples

import (
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
	psh "github.com/platformsh/config-reader-go/v2"
	libpq "github.com/platformsh/config-reader-go/v2/libpq"
)

func UsageExamplePostgreSQL() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// The 'database' relationship is generally the name of the primary SQL database of an application.
	// It could be anything, though, as in the case here where it's called "postgresql".
	credentials, err := config.Credentials("postgresql")
	checkErr(err)

	// Retrieve the formatted credentials.
	formatted, err := libpq.FormattedCredentials(credentials)
	checkErr(err)

	// Connect.
	db, err := sql.Open("postgres", formatted)
	checkErr(err)

	defer db.Close()

	// Creating a table.
	sqlCreate := "CREATE TABLE IF NOT EXISTS PeopleGo (" +
		"id SERIAL PRIMARY KEY," +
		"name VARCHAR(30) NOT NULL," +
		"city VARCHAR(30) NOT NULL);"

	_, err = db.Exec(sqlCreate)
	checkErr(err)

	// Insert data.
	sqlInsert := "INSERT INTO PeopleGo(name, city) VALUES" +
		"('Neil Armstrong', 'Moon')," +
		"('Buzz Aldrin', 'Glen Ridge')," +
		"('Sally Ride', 'La Jolla');"

	_, err = db.Exec(sqlInsert)
	checkErr(err)

	table := "<table>" +
		"<thead>" +
		"<tr><th>Name</th><th>City</th></tr>" +
		"</thead>" +
		"<tbody>"

	var id int
	var name string
	var city string

	// Read it back.
	rows, err := db.Query("SELECT * FROM PeopleGo")
	if err != nil {
		panic(err)
	} else {
		for rows.Next() {
			err = rows.Scan(&id, &name, &city)
			checkErr(err)
			table += fmt.Sprintf("<tr><td>%s</td><td>%s</td><tr>\n", name, city)
		}
		table += "</tbody>\n</table>\n"
	}

	_, err = db.Exec("DROP TABLE PeopleGo;")
	checkErr(err)

	return table
}

Output

NameCity
Neil ArmstrongMoon
Buzz AldrinGlen Ridge
Sally RideLa Jolla
RabbitMQ Sample Code

Source

package examples

import (
	"fmt"
	psh "github.com/platformsh/config-reader-go/v2"
	amqpPsh "github.com/platformsh/config-reader-go/v2/amqp"
	"github.com/streadway/amqp"
	"sync"
)

func UsageExampleRabbitMQ() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// Get the credentials to connect to RabbitMQ.
	credentials, err := config.Credentials("rabbitmq")
	checkErr(err)

	// Use the amqp formatted credentials package.
	formatted, err := amqpPsh.FormattedCredentials(credentials)
	checkErr(err)

	// Connect to the RabbitMQ server.
	connection, err := amqp.Dial(formatted)
	checkErr(err)
	defer connection.Close()

	// Make a channel.
	channel, err := connection.Channel()
	checkErr(err)
	defer channel.Close()

	// Create a queue.
	q, err := channel.QueueDeclare(
		"deploy_days", // name
		false,         // durable
		false,         // delete when unused
		false,         // exclusive
		false,         // no-wait
		nil,           // arguments
	)

	body := "Friday"
	msg := fmt.Sprintf("Deploying on %s", body)

	// Publish a message.
	err = channel.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(msg),
		})
	checkErr(err)

	outputMSG := fmt.Sprintf("[x] Sent '%s' <br>", body)

	// Consume the message.
	msgs, err := channel.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	checkErr(err)

	var received string
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		for d := range msgs {
			received = fmt.Sprintf("[x] Received message: '%s' <br>", d.Body)
			wg.Done()
		}
	}()

	wg.Wait()

	outputMSG += received

	return outputMSG
}

Output

[x] Sent 'Friday'
[x] Received message: 'Deploying on Friday'
Solr Sample Code

Source

package examples

import (
	"fmt"

	psh "github.com/platformsh/config-reader-go/v2"
	gosolr "github.com/platformsh/config-reader-go/v2/gosolr"
	solr "github.com/rtt/Go-Solr"
)

func UsageExampleSolr() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// Get the credentials to connect to the Solr service.
	credentials, err := config.Credentials("solr")
	checkErr(err)

	// Retrieve Solr formatted credentials.
	formatted, err := gosolr.FormattedCredentials(credentials)
	checkErr(err)

	// Connect to Solr using the formatted credentials.
	connection := &solr.Connection{URL: formatted}

	// Add a document and commit the operation.
	docAdd := map[string]interface{}{
		"add": []interface{}{
			map[string]interface{}{"id": 123, "name": "Valentina Tereshkova"},
		},
	}

	respAdd, err := connection.Update(docAdd, true)
	checkErr(err)

	// Select the document.
	q := &solr.Query{
		Params: solr.URLParamMap{
			"q": []string{"id:123"},
		},
	}

	resSelect, err := connection.CustomSelect(q, "query")
	checkErr(err)

	// Delete the document and commit the operation.
	docDelete := map[string]interface{}{
		"delete": map[string]interface{}{
			"id": 123,
		},
	}

	resDel, err := connection.Update(docDelete, true)
	checkErr(err)

	message := fmt.Sprintf("Adding one document - %s<br>"+
		"Selecting document (1 expected): %d<br>"+
		"Deleting document - %s<br>",
		respAdd, resSelect.Results.NumFound, resDel)

	return message
}

Output

Adding one document - UpdateResponse: OK
Selecting document (1 expected): 1
Deleting document - UpdateResponse: OK