Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
I

influxdb-client-go

> 开发工具
Open source

InfluxDB 2 Go Client

652 stars0 likes0 views
WebsiteGitHub

About

InfluxDB 2 Go Client

InfluxDB Client Go

This repository contains the Go client library for use with InfluxDB 2.x and Flux. InfluxDB 3.x users should instead use the lightweight v3 client library. InfluxDB 1.x users should use the v1 client library.

For ease of migration and a consistent query and write experience, v2 users should consider using InfluxQL and the v1 client library.

  • Features
  • Documentation
    • Examples
  • How To Use
    • Installation
    • Basic Example
    • Writes in Detail
    • Queries in Detail
    • Parametrized Queries
    • Concurrency
    • Proxy and redirects
    • Checking Server State
  • InfluxDB 1.8 API compatibility
  • Contributing
  • License

Features

  • InfluxDB 2 client
    • Querying data
      • using the Flux language
      • into raw data, flux table representation
      • How to queries
    • Writing data using
      • Line Protocol
      • Data Point
      • Both asynchronous or synchronous ways
      • How to writes
    • InfluxDB 2 API
      • setup, ready, health
      • authotizations, users, organizations
      • buckets, delete
      • ...

Documentation

This section contains links to the client library documentation.

  • Product documentation, Getting Started
  • Examples
  • API Reference
  • Changelog

Examples

Examples for basic writing and querying data are shown below in this document

There are also other examples in the API docs:

  • Client usage
  • Management APIs

How To Use

Installation

Go 1.17 or later is required.

Go mod project

  1. Add the latest version of the client package to your project dependencies (go.mod).
    go get github.com/influxdata/influxdb-client-go/v2
    
  2. Add import github.com/influxdata/influxdb-client-go/v2 to your source code.

GOPATH project

go get github.com/influxdata/influxdb-client-go

Note: To have go get in the GOPATH mode, the environment variable GO111MODULE must have the off value.

Basic Example

The following example demonstrates how to write data to InfluxDB 2 and read them back using the Flux language:

…

Options

The InfluxDBClient uses set of options to configure behavior. These are available in the Options object Creating a client instance using

client := influxdb2.NewClient("http://localhost:8086", "my-token")

will use the default options.

To set different configuration values, e.g. to set gzip compression and trust all server certificates, get default options and change what is needed:

client := influxdb2.NewClientWithOptions("http://localhost:8086", "my-token",
    influxdb2.DefaultOptions().
        SetUseGZip(true).
        SetTLSConfig(&tls.Config{
            InsecureSkipVerify: true,
        }))

Writes

Client offers two ways of writing, non-blocking and blocking.

Non-blocking write client

Non-blocking write client uses implicit batching. Data are asynchronously written to the underlying buffer and they are automatically sent to a server when the size of the write buffer reaches the batch size, default 5000, or the flush interval, default 1s, times out. Writes are automatically retried on server back pressure.

This write client also offers synchronous blocking method to ensure that write buffer is flushed and all pending writes are finished, see Flush() method. Always use Close() method of the client to stop all background processes.

Asynchronous write client is recommended for frequent periodic writes.

…

go package main

import ( "fmt" "math/rand" "time"

"github.com/influxdata/influxdb-client-go/v2"

)

func main() { // Create a new client using an InfluxDB server base URL and an authentication token client := influxdb2.NewClient("http://localhost:8086", "my-token") // Get non-blocking write client writeAPI := client.WriteAPI("my-org", "my-bucket") // Get errors channel errorsCh := writeAPI.Errors() // Create go proc for reading and logging errors go func() { for err := range errorsCh { fmt.Printf("write error: %s\n", err.Error()) } }() // write some points for i := 0; i range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`) if err == nil { // Iterate over query response for result.Next() { // Notice when group key has changed if result.TableChanged() { fmt.Printf("table: %s\n", result.TableMetadata().String()) } // Access data fmt.Printf("value: %v\n", result.Record().Value()) } // check for an error if result.Err() != nil { fmt.Printf("query parsing error: %s\n", result.Err().Error()) } } else { panic(err) } // Ensures background processes finishes client.Close() }


### Raw
[QueryRaw()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#QueryAPI.QueryRaw) returns raw, unparsed, query result string and process it on your own. Returned csv format
can be controlled by the third parameter, query dialect.

```go
package main

import (
    "context"
    "fmt"

    "github.com/influxdata/influxdb-client-go/v2"
)

func main() {
    // Create a new client using an InfluxDB server base URL and an authentication token
    client := influxdb2.NewClient("http://localhost:8086", "my-token")
    // Get query client
    queryAPI := client.QueryAPI("my-org")
    // Query and get complete result as a string
    // Use default dialect
    result, err := queryAPI.QueryRaw(context.Background(), `from(bucket:"my-bucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`, influxdb2.DefaultDialect())
    if err == nil {
        fmt.Println("QueryResult:")
        fmt.Println(result)
    } else {
        panic(err)
    }
    // Ensures background processes finishes
    client.Close()
}

…

go
package main

import (
	"context"
	"fmt"

	"github.com/influxdata/influxdb-client-go/v2"
)

func main() {
	// Create a new client using an InfluxDB server base URL and an authentication token
	client := influxdb2.NewClient("http://localhost:8086", "my-token")
	// Get query client
	queryAPI := client.QueryAPI("my-org")
	// Define parameters
	parameters := struct {
		Start string  `json:"start"`
		Field string  `json:"field"`
		Value float64 `json:"value"`
	}{
		"-1h",
		"temperature",
		25,
	}
	// Query with parameters
	query := `from(bucket:"my-bucket")
				|> range(start: duration(params.start))
				|> filter(fn: (r) => r._measurement == "stat")
				|> filter(fn: (r) => r._field == params.field)
				|> filter(fn: (r) => r._value > params.value)`

	// Get result
	result, err := queryAPI.QueryWithParams(context.Background(), query, parameters)
	if err == nil {
		// Iterate over query response
		for result.Next() {
			// Notice when group key has changed
			if result.TableChanged() {
				fmt.Printf("table: %s\n", result.TableMetadata().String())
			}
			// Access data
			fmt.Printf("value: %v\n", result.Record().Value())
		}
		// check for an error
		if result.Err() != nil {
			fmt.Printf("query parsing error: %s\n", result.Err().Error())
		}
	} else {
		panic(err)
	}
	// Ensures background processes finishes
	client.Close()
}

Concurrency

InfluxDB Go Client can be used in a concurrent environment. All its functions are thread-safe.

The best practise is to use a single Client instance per server URL. This ensures optimized resources usage, most importantly reusing HTTP connections.

For efficient reuse of HTTP resources among multiple clients, create an HTTP client and use Options.SetHTTPClient() for setting it to all clients:

    // Create HTTP client
    httpClient := &http.Client{
        Timeout: time.Second * time.Duration(60),
        Transport: &http.Transport{
            DialContext: (&net.Dialer{
                Timeout: 5 * time.Second,
            }).DialContext,
            TLSHandshakeTimeout: 5 * time.Second,
            TLSClientConfig: &tls.Config{
                InsecureSkipVerify: true,
            },
            MaxIdleConns:        100,
            MaxIdleConnsPerHost: 100,
            IdleConnTimeout:     90 * time.Second,
        },
    }
    // Client for server 1
    client1 := influxdb2.NewClientWithOptions("https://server:8086", "my-token", influxdb2.DefaultOptions().SetHTTPClient(httpClient))
    // Client for server 2
    client2 := influxdb2.NewClientWithOptions("https://server:9999", "my-token2", influxdb2.DefaultOptions().SetHTTPClient(httpClient))

Client ensures that there is a single instance of each server API sub-client for the specific area. E.g. a single WriteAPI instance for each org/bucket pair, a single QueryAPI for each org.

Such a single API sub-client instance can be used concurrently:

package main

import (
	"math/rand"
	"sync"
	"time"

	influxdb2 "github.com/influxdata/influxdb-client-go"
	"github.com/influxdata/influxdb-client-go/v2/api/write"
)

func main() {
    // Create client
    client := influxdb2.NewClient("http://localhost:8086", "my-token")
    // Ensure closing the client
    defer client.Close()

    // Get write client
    writeApi := client.WriteAPI("my-org", "my-bucket")

    // Create channel for points feeding
    pointsCh := make(chan *write.Point, 200)

    threads := 5

    var wg sync.WaitGroup
    go func(points int) {
        for i := 0; i  range(start: -1h) |> filter(fn: (r) => r._measurement == "stat")`)
    if err == nil {
        for result.Next() {
            if result.TableChanged() {
                fmt.Printf("table: %s\n", result.TableMetadata().String())
            }
            fmt.Printf("row: %s\n", result.Record().String())
        }
        if result.Err() != nil {
            fmt.Printf("Query error: %s\n", result.Err().Error())
        }
    } else {
        fmt.Printf("Query error: %s\n", err.Error())
    }
    // Close client
    client.Close()
}

Contributing

If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master branch.

License

The InfluxDB 2 Go Client is released under the MIT License.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gogogolanggolang-clientinfluxdb

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具