Write data to M3DB with Go#

This example writes some data to an M3DB service from Go, making use of the Prometheus write features.

Variables#

These are the placeholders you will need to replace in the code sample:

Variable

Description

PROM_WRITE_URL

URL for Prometheus writes, from the service overview page

Pre-requisites#

For this example you will need:

  1. The Prometheus client for Go:

    go get -u github.com/m3db/prometheus_remote_client_golang/promremote
    

Code#

Add the following to main.go and replace the PROM_WRITE_URL placeholder:

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/m3db/prometheus_remote_client_golang/promremote"
)

func main() {
	cfg := promremote.NewConfig(
		promremote.WriteURLOption(PROM_WRITE_URL),
		promremote.HTTPClientTimeoutOption(60*time.Second),
		promremote.UserAgent("aiven-docs/0.1"),
	)
	client, err := promremote.NewClient(cfg)
	if err != nil {
		log.Fatal(fmt.Errorf("unable to construct client: %v", err))
	}
	timeSeriesList := []promremote.TimeSeries{
		{
			Labels: []promremote.Label{
				{
					Name:  "__name__",
					Value: "cpu_temp_instant",
				},
			},
			Datapoint: promremote.Datapoint{
				Timestamp: time.Now(),
				Value:     83.0,
			},
		},
	}

	var ctx = context.Background()
	var writeOpts promremote.WriteOptions
	result, err := client.WriteTimeSeries(ctx, timeSeriesList, writeOpts)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Status code: %d\n", result.StatusCode)
}

Since M3DB also supports Prometheus-style writes, this code sets up a Prometheus client and then constructs the expected data format to send to M3DB.

To run the code:

go run main.go

If the script outputs Status code: 200 then there is data in your M3DB. See Visualize M3DB data with Grafana.