Go client library

Use the InfluxDB Go client library to integrate InfluxDB into Go scripts and applications.

This guide presumes some familiarity with Go and InfluxDB. If just getting started, see Get started with InfluxDB.

Before you begin

  1. Install Go 1.13 or later.
  2. Add the client package your to your project dependencies.

    1. # Add InfluxDB Go client package to your project go.mod
    2. go get github.com/influxdata/influxdb-client-go/v2
  3. Ensure that InfluxDB is running and you can connect to it. For information about what URL to use to connect to InfluxDB OSS or InfluxDB Cloud, see InfluxDB URLs.

Boilerplate for the InfluxDB Go Client Library

Use the Go library to write and query data from InfluxDB.

  1. In your Go program, import the necessary packages and specify the entry point of your executable program.

    1. package main
    2. import (
    3. "context"
    4. "fmt"
    5. "time"
    6. "github.com/influxdata/influxdb-client-go/v2"
    7. )
  2. Define variables for your InfluxDB bucket, organization, and token.

    1. bucket := "example-bucket"
    2. org := "example-org"
    3. token := "example-token"
    4. // Store the URL of your InfluxDB instance
    5. url := "http://localhost:8086"
  3. Create the the InfluxDB Go client and pass in the url and token parameters.

    1. client := influxdb2.NewClient(url, token)
  4. Create a write client with the WriteAPIBlocking method and pass in the org and bucket parameters.

    1. writeAPI := client.WriteAPIBlocking(org, bucket)
  5. To query data, create an InfluxDB query client and pass in your InfluxDB org.

    1. queryAPI := client.QueryAPI(org)

Write data to InfluxDB with Go

Use the Go library to write data to InfluxDB.

  1. Create a point and write it to InfluxDB using the WritePoint method of the API writer struct.

  2. Close the client to flush all pending writes and finish.

    1. p := influxdb2.NewPoint("stat",
    2. map[string]string{"unit": "temperature"},
    3. map[string]interface{}{"avg": 24.5, "max": 45},
    4. time.Now())
    5. writeAPI.WritePoint(context.Background(), p)
    6. client.Close()

Complete example write script

  1. func main() {
  2. bucket := "example-bucket"
  3. org := "example-org"
  4. token := "example-token"
  5. // Store the URL of your InfluxDB instance
  6. url := "http://localhost:8086"
  7. // Create new client with default option for server url authenticate by token
  8. client := influxdb2.NewClient(url, token)
  9. // User blocking write client for writes to desired bucket
  10. writeAPI := client.WriteAPIBlocking(org, bucket)
  11. // Create point using full params constructor
  12. p := influxdb2.NewPoint("stat",
  13. map[string]string{"unit": "temperature"},
  14. map[string]interface{}{"avg": 24.5, "max": 45},
  15. time.Now())
  16. // Write point immediately
  17. writeAPI.WritePoint(context.Background(), p)
  18. // Ensures background processes finishes
  19. client.Close()
  20. }

Query data from InfluxDB with Go

Use the Go library to query data to InfluxDB.

  1. Create a Flux query and supply your bucket parameter.

    1. from(bucket:"<bucket>")
    2. |> range(start: -1h)
    3. |> filter(fn: (r) => r._measurement == "stat")

The query client sends the Flux query to InfluxDB and returns the results as a FluxRecord object with a table structure.

The query client includes the following methods:

  • Query: Sends the Flux query to InfluxDB.
  • Next: Iterates over the query response.
  • TableChanged: Identifies when the group key changes.
  • Record: Returns the last parsed FluxRecord and gives access to value and row properties.
  • Value: Returns the actual field value.

    1. result, err := queryAPI.Query(context.Background(), `from(bucket:"<bucket>")
    2. |> range(start: -1h)
    3. |> filter(fn: (r) => r._measurement == "stat")`)
    4. if err == nil {
    5. for result.Next() {
    6. if result.TableChanged() {
    7. fmt.Printf("table: %s\n", result.TableMetadata().String())
    8. }
    9. fmt.Printf("value: %v\n", result.Record().Value())
    10. }
    11. if result.Err() != nil {
    12. fmt.Printf("query parsing error: %s\n", result.Err().Error())
    13. }
    14. } else {
    15. panic(err)
    16. }

The FluxRecord object includes the following methods for accessing your data:

  • Table(): Returns the index of the table the record belongs to.
  • Start(): Returns the inclusive lower time bound of all records in the current table.
  • Stop(): Returns the exclusive upper time bound of all records in the current table.
  • Time(): Returns the time of the record.
  • Value(): Returns the actual field value.
  • Field(): Returns the field name.
  • Measurement(): Returns the measurement name of the record.
  • Values(): Returns a map of column values.
  • ValueByKey(<your_tags>): Returns a value from the record for given column key.

Complete example query script

  1. func main() {
  2. // Create client
  3. client := influxdb2.NewClient(url, token)
  4. // Get query client
  5. queryAPI := client.QueryAPI(org)
  6. // Get QueryTableResult
  7. result, err := queryAPI.Query(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`)
  8. if err == nil {
  9. // Iterate over query response
  10. for result.Next() {
  11. // Notice when group key has changed
  12. if result.TableChanged() {
  13. fmt.Printf("table: %s\n", result.TableMetadata().String())
  14. }
  15. // Access data
  16. fmt.Printf("value: %v\n", result.Record().Value())
  17. }
  18. // Check for an error
  19. if result.Err() != nil {
  20. fmt.Printf("query parsing error: %s\n", result.Err().Error())
  21. }
  22. } else {
  23. panic(err)
  24. }
  25. // Ensures background processes finishes
  26. client.Close()
  27. }

For more information, see the Go client README on GitHub.

client libraries Go