{"id":13491673,"url":"https://github.com/influxdata/influxdb-client-go","last_synced_at":"2025-05-13T00:06:12.253Z","repository":{"id":38905615,"uuid":"178956163","full_name":"influxdata/influxdb-client-go","owner":"influxdata","description":"InfluxDB 2 Go Client","archived":false,"fork":false,"pushed_at":"2025-04-18T11:23:10.000Z","size":1382,"stargazers_count":634,"open_issues_count":21,"forks_count":118,"subscribers_count":53,"default_branch":"master","last_synced_at":"2025-05-13T00:06:01.045Z","etag":null,"topics":["go","golang","golang-client","influxdb","influxdb-client"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/influxdata.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-04-01T22:24:10.000Z","updated_at":"2025-05-12T17:07:15.000Z","dependencies_parsed_at":"2023-11-22T07:24:36.712Z","dependency_job_id":"10ee5d36-cda8-4b6f-80f2-5dd33a962458","html_url":"https://github.com/influxdata/influxdb-client-go","commit_stats":null,"previous_names":["influxdata/influxdb2-go"],"tags_count":41,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influxdata%2Finfluxdb-client-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influxdata%2Finfluxdb-client-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influxdata%2Finfluxdb-client-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influxdata%2Finfluxdb-client-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/influxdata","download_url":"https://codeload.github.com/influxdata/influxdb-client-go/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253843215,"owners_count":21972873,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["go","golang","golang-client","influxdb","influxdb-client"],"created_at":"2024-07-31T19:00:59.288Z","updated_at":"2025-05-13T00:06:12.218Z","avatar_url":"https://github.com/influxdata.png","language":"Go","funding_links":[],"categories":["Go"],"sub_categories":[],"readme":"# InfluxDB Client Go\n\n[![CircleCI](https://circleci.com/gh/influxdata/influxdb-client-go.svg?style=svg)](https://circleci.com/gh/influxdata/influxdb-client-go)\n[![codecov](https://codecov.io/gh/influxdata/influxdb-client-go/branch/master/graph/badge.svg)](https://codecov.io/gh/influxdata/influxdb-client-go)\n[![License](https://img.shields.io/github/license/influxdata/influxdb-client-go.svg)](https://github.com/influxdata/influxdb-client-go/blob/master/LICENSE)\n[![Slack Status](https://img.shields.io/badge/slack-join_chat-white.svg?logo=slack\u0026style=social)](https://www.influxdata.com/slack)\n\nThis 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](https://github.com/InfluxCommunity/influxdb3-go). InfluxDB 1.x users should use the [v1 client library](https://github.com/influxdata/influxdb/tree/1.8/client).\n\nFor ease of migration and a consistent query and write experience, v2 users should consider using InfluxQL and the [v1 client library](https://github.com/influxdata/influxdb/tree/1.8/client).\n\n- [Features](#features)\n- [Documentation](#documentation)\n    - [Examples](#examples)\n- [How To Use](#how-to-use)\n    - [Installation](#installation)\n    - [Basic Example](#basic-example)\n    - [Writes in Detail](#writes)\n    - [Queries in Detail](#queries)\n    - [Parametrized Queries](#parametrized-queries)\n    - [Concurrency](#concurrency)\n    - [Proxy and redirects](#proxy-and-redirects)\n    - [Checking Server State](#checking-server-state)\n- [InfluxDB 1.8 API compatibility](#influxdb-18-api-compatibility)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Features\n\n- InfluxDB 2 client\n    - Querying data\n        - using the Flux language\n        - into raw data, flux table representation\n        - [How to queries](#queries)\n    - Writing data using\n        - [Line Protocol](https://docs.influxdata.com/influxdb/v2.0/reference/syntax/line-protocol/)\n        - [Data Point](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api/write#Point)\n        - Both [asynchronous](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#WriteAPI) or [synchronous](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#WriteAPIBlocking) ways\n        - [How to writes](#writes)\n    - InfluxDB 2 API\n        - setup, ready, health\n        - authotizations, users, organizations\n        - buckets, delete\n        - ...\n\n## Documentation\n\nThis section contains links to the client library documentation.\n\n- [Product documentation](https://docs.influxdata.com/influxdb/v2.0/tools/client-libraries/), [Getting Started](#how-to-use)\n- [Examples](#examples)\n- [API Reference](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2)\n- [Changelog](CHANGELOG.md)\n\n### Examples\n\nExamples for basic writing and querying data are shown below in this document\n\nThere are also other examples in the API docs:\n - [Client usage](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2?tab=doc#pkg-examples)\n - [Management APIs](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api?tab=doc#pkg-examples)\n\n## How To Use\n\n### Installation\n**Go 1.17** or later is required.\n\n#### Go mod project\n1.  Add the latest version of the client package to your project dependencies (go.mod).\n    ```sh\n    go get github.com/influxdata/influxdb-client-go/v2\n    ```\n1. Add import `github.com/influxdata/influxdb-client-go/v2` to your source code.\n#### GOPATH project\n```sh\ngo get github.com/influxdata/influxdb-client-go\n```\nNote: To have _go get_ in the GOPATH mode, the environment variable `GO111MODULE` must have the `off` value.\n\n### Basic Example\nThe following example demonstrates how to write data to InfluxDB 2 and read them back using the Flux language:\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n\n    \"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n    // Create a new client using an InfluxDB server base URL and an authentication token\n    client := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n    // Use blocking write client for writes to desired bucket\n    writeAPI := client.WriteAPIBlocking(\"my-org\", \"my-bucket\")\n    // Create point using full params constructor\n    p := influxdb2.NewPoint(\"stat\",\n        map[string]string{\"unit\": \"temperature\"},\n        map[string]interface{}{\"avg\": 24.5, \"max\": 45.0},\n        time.Now())\n    // write point immediately\n    writeAPI.WritePoint(context.Background(), p)\n    // Create point using fluent style\n    p = influxdb2.NewPointWithMeasurement(\"stat\").\n        AddTag(\"unit\", \"temperature\").\n        AddField(\"avg\", 23.2).\n        AddField(\"max\", 45.0).\n        SetTime(time.Now())\n    err := writeAPI.WritePoint(context.Background(), p)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n    // Or write directly line protocol\n    line := fmt.Sprintf(\"stat,unit=temperature avg=%f,max=%f\", 23.5, 45.0)\n    err = writeAPI.WriteRecord(context.Background(), line)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n    // Get query client\n    queryAPI := client.QueryAPI(\"my-org\")\n    // Get parser flux query result\n    result, err := queryAPI.Query(context.Background(), `from(bucket:\"my-bucket\")|\u003e range(start: -1h) |\u003e filter(fn: (r) =\u003e r._measurement == \"stat\")`)\n    if err == nil {\n        // Use Next() to iterate over query result lines\n        for result.Next() {\n            // Observe when there is new grouping key producing new table\n            if result.TableChanged() {\n                fmt.Printf(\"table: %s\\n\", result.TableMetadata().String())\n            }\n            // read result\n            fmt.Printf(\"row: %s\\n\", result.Record().String())\n        }\n        if result.Err() != nil {\n            fmt.Printf(\"Query error: %s\\n\", result.Err().Error())\n        }\n    } else {\n\t\tpanic(err)\n    }\n    // Ensures background processes finishes\n    client.Close()\n}\n```\n### Options\nThe InfluxDBClient uses set of options to configure behavior. These are available in the [Options](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2#Options) object\nCreating a client instance using\n```go\nclient := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n```\nwill use the default options.\n\nTo set different configuration values, e.g. to set gzip compression and trust all server certificates, get default options\nand change what is needed:\n```go\nclient := influxdb2.NewClientWithOptions(\"http://localhost:8086\", \"my-token\",\n    influxdb2.DefaultOptions().\n        SetUseGZip(true).\n        SetTLSConfig(\u0026tls.Config{\n            InsecureSkipVerify: true,\n        }))\n```\n### Writes\n\nClient offers two ways of writing, non-blocking and blocking.\n\n### Non-blocking write client\nNon-blocking write client uses implicit batching. Data are asynchronously\nwritten 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.\nWrites are automatically retried on server back pressure.\n\nThis write client also offers synchronous blocking method to ensure that write buffer is flushed and all pending writes are finished,\nsee [Flush()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#WriteAPI.Flush) method.\nAlways use [Close()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2#Client.Close) method of the client to stop all background processes.\n\nAsynchronous write client is recommended for frequent periodic writes.\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n\n    \"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n    // Create a new client using an InfluxDB server base URL and an authentication token\n    // and set batch size to 20\n    client := influxdb2.NewClientWithOptions(\"http://localhost:8086\", \"my-token\",\n        influxdb2.DefaultOptions().SetBatchSize(20))\n    // Get non-blocking write client\n    writeAPI := client.WriteAPI(\"my-org\",\"my-bucket\")\n    // write some points\n    for i := 0; i \u003c100; i++ {\n        // create point\n        p := influxdb2.NewPoint(\n            \"system\",\n            map[string]string{\n                \"id\":       fmt.Sprintf(\"rack_%v\", i%10),\n                \"vendor\":   \"AWS\",\n                \"hostname\": fmt.Sprintf(\"host_%v\", i%100),\n            },\n            map[string]interface{}{\n                \"temperature\": rand.Float64() * 80.0,\n                \"disk_free\":   rand.Float64() * 1000.0,\n                \"disk_total\":  (i/10 + 1) * 1000000,\n                \"mem_total\":   (i/100 + 1) * 10000000,\n                \"mem_free\":    rand.Uint64(),\n            },\n            time.Now())\n        // write asynchronously\n        writeAPI.WritePoint(p)\n    }\n    // Force all unwritten data to be sent\n    writeAPI.Flush()\n    // Ensures background processes finishes\n    client.Close()\n}\n```\n### Handling of failed async writes\nWriteAPI by default continues with retrying of failed writes.\nRetried are automatically writes that fail on a connection failure or when server returns response HTTP status code \u003e= 429.\n\nRetrying algorithm uses random exponential strategy to set retry time.\nThe delay for the next retry attempt is a random value in the interval _retryInterval * exponentialBase^(attempts)_ and _retryInterval * exponentialBase^(attempts+1)_.\nIf writes of batch repeatedly fails, WriteAPI continues with retrying until _maxRetries_ is reached or the overall retry time of batch exceeds _maxRetryTime_.\n\nThe defaults parameters (part of the WriteOptions) are:\n - _retryInterval_=5,000ms\n - _exponentialBase_=2\n - _maxRetryDelay_=125,000ms\n - _maxRetries_=5\n - _maxRetryTime_=180,000ms\n\nRetry delays are by default randomly distributed within the ranges:\n 1. 5,000-10,000\n 1. 10,000-20,000\n 1. 20,000-40,000\n 1. 40,000-80,000\n 1. 80,000-125,000\n\nSetting _retryInterval_ to 0 disables retry strategy and any failed write will discard the batch.\n\n[WriteFailedCallback](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#WriteFailedCallback) allows advanced controlling of retrying.\nIt is synchronously notified in case async write fails.\nIt controls further batch handling by its return value. If it returns `true`, WriteAPI continues with retrying of writes of this batch. Returned `false` means the batch should be discarded.\n\n### Reading async errors\nWriteAPI automatically logs write errors. Use [Errors()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#WriteAPI.Errors) method, which returns the channel for reading errors occuring during async writes, for writing write error to a custom target:\n\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n\n    \"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n    // Create a new client using an InfluxDB server base URL and an authentication token\n    client := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n    // Get non-blocking write client\n    writeAPI := client.WriteAPI(\"my-org\", \"my-bucket\")\n    // Get errors channel\n    errorsCh := writeAPI.Errors()\n    // Create go proc for reading and logging errors\n    go func() {\n        for err := range errorsCh {\n            fmt.Printf(\"write error: %s\\n\", err.Error())\n        }\n    }()\n    // write some points\n    for i := 0; i \u003c 100; i++ {\n        // create point\n        p := influxdb2.NewPointWithMeasurement(\"stat\").\n            AddTag(\"id\", fmt.Sprintf(\"rack_%v\", i%10)).\n            AddTag(\"vendor\", \"AWS\").\n            AddTag(\"hostname\", fmt.Sprintf(\"host_%v\", i%100)).\n            AddField(\"temperature\", rand.Float64()*80.0).\n            AddField(\"disk_free\", rand.Float64()*1000.0).\n            AddField(\"disk_total\", (i/10+1)*1000000).\n            AddField(\"mem_total\", (i/100+1)*10000000).\n            AddField(\"mem_free\", rand.Uint64()).\n            SetTime(time.Now())\n        // write asynchronously\n        writeAPI.WritePoint(p)\n    }\n    // Force all unwritten data to be sent\n    writeAPI.Flush()\n    // Ensures background processes finishes\n    client.Close()\n}\n```\n\n### Blocking write client\nBlocking write client writes given point(s) synchronously. It doesn't do implicit batching. Batch is created from given set of points.\nImplicit batching can be enabled with `WriteAPIBlocking.EnableBatching()`.\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"math/rand\"\n    \"time\"\n\n    \"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n    // Create a new client using an InfluxDB server base URL and an authentication token\n    client := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n    // Get blocking write client\n    writeAPI := client.WriteAPIBlocking(\"my-org\",\"my-bucket\")\n    // write some points\n    for i := 0; i \u003c100; i++ {\n        // create data point\n        p := influxdb2.NewPoint(\n            \"system\",\n            map[string]string{\n                \"id\":       fmt.Sprintf(\"rack_%v\", i%10),\n                \"vendor\":   \"AWS\",\n                \"hostname\": fmt.Sprintf(\"host_%v\", i%100),\n            },\n            map[string]interface{}{\n                \"temperature\": rand.Float64() * 80.0,\n                \"disk_free\":   rand.Float64() * 1000.0,\n                \"disk_total\":  (i/10 + 1) * 1000000,\n                \"mem_total\":   (i/100 + 1) * 10000000,\n                \"mem_free\":    rand.Uint64(),\n            },\n            time.Now())\n        // write synchronously\n        err := writeAPI.WritePoint(context.Background(), p)\n        if err != nil {\n            panic(err)\n        }\n    }\n    // Ensures background processes finishes\n    client.Close()\n}\n```\n\n### Queries\nQuery client offers retrieving of query results to a parsed representation in a [QueryTableResult](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#QueryTableResult) or to a raw string.\n\n### QueryTableResult\nQueryTableResult offers comfortable way how to deal with flux query CSV response. It parses CSV stream into FluxTableMetaData, FluxColumn and FluxRecord objects\nfor easy reading the result.\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n    // Create a new client using an InfluxDB server base URL and an authentication token\n    client := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n    // Get query client\n    queryAPI := client.QueryAPI(\"my-org\")\n    // get QueryTableResult\n    result, err := queryAPI.Query(context.Background(), `from(bucket:\"my-bucket\")|\u003e range(start: -1h) |\u003e filter(fn: (r) =\u003e r._measurement == \"stat\")`)\n    if err == nil {\n        // Iterate over query response\n        for result.Next() {\n            // Notice when group key has changed\n            if result.TableChanged() {\n                fmt.Printf(\"table: %s\\n\", result.TableMetadata().String())\n            }\n            // Access data\n            fmt.Printf(\"value: %v\\n\", result.Record().Value())\n        }\n        // check for an error\n        if result.Err() != nil {\n            fmt.Printf(\"query parsing error: %s\\n\", result.Err().Error())\n        }\n    } else {\n        panic(err)\n    }\n    // Ensures background processes finishes\n    client.Close()\n}\n```\n\n### Raw\n[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\ncan be controlled by the third parameter, query dialect.\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n    // Create a new client using an InfluxDB server base URL and an authentication token\n    client := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n    // Get query client\n    queryAPI := client.QueryAPI(\"my-org\")\n    // Query and get complete result as a string\n    // Use default dialect\n    result, err := queryAPI.QueryRaw(context.Background(), `from(bucket:\"my-bucket\")|\u003e range(start: -1h) |\u003e filter(fn: (r) =\u003e r._measurement == \"stat\")`, influxdb2.DefaultDialect())\n    if err == nil {\n        fmt.Println(\"QueryResult:\")\n        fmt.Println(result)\n    } else {\n        panic(err)\n    }\n    // Ensures background processes finishes\n    client.Close()\n}\n```\n### Parametrized Queries\nInfluxDB Cloud supports [Parameterized Queries](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/)\nthat let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more\nreusable and can also be used to help prevent injection attacks.\n\nInfluxDB Cloud inserts the params object into the Flux query as a Flux record named `params`. Use dot or bracket\nnotation to access parameters in the `params` record in your Flux query. Parameterized Flux queries support only `int`\n, `float`, and `string` data types. To convert the supported data types into\nother [Flux basic data types, use Flux type conversion functions](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/#supported-parameter-data-types).\n\nQuery parameters can be passed as a struct or map. Param values can be only simple types or `time.Time`.\nThe name of the parameter represented by a struct field can be specified by JSON annotation.\n\nParameterized query example:\n\u003e :warning: Parameterized Queries are supported only in InfluxDB Cloud. There is no support in InfluxDB OSS currently.\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n\t// Create a new client using an InfluxDB server base URL and an authentication token\n\tclient := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n\t// Get query client\n\tqueryAPI := client.QueryAPI(\"my-org\")\n\t// Define parameters\n\tparameters := struct {\n\t\tStart string  `json:\"start\"`\n\t\tField string  `json:\"field\"`\n\t\tValue float64 `json:\"value\"`\n\t}{\n\t\t\"-1h\",\n\t\t\"temperature\",\n\t\t25,\n\t}\n\t// Query with parameters\n\tquery := `from(bucket:\"my-bucket\")\n\t\t\t\t|\u003e range(start: duration(params.start))\n\t\t\t\t|\u003e filter(fn: (r) =\u003e r._measurement == \"stat\")\n\t\t\t\t|\u003e filter(fn: (r) =\u003e r._field == params.field)\n\t\t\t\t|\u003e filter(fn: (r) =\u003e r._value \u003e params.value)`\n\n\t// Get result\n\tresult, err := queryAPI.QueryWithParams(context.Background(), query, parameters)\n\tif err == nil {\n\t\t// Iterate over query response\n\t\tfor result.Next() {\n\t\t\t// Notice when group key has changed\n\t\t\tif result.TableChanged() {\n\t\t\t\tfmt.Printf(\"table: %s\\n\", result.TableMetadata().String())\n\t\t\t}\n\t\t\t// Access data\n\t\t\tfmt.Printf(\"value: %v\\n\", result.Record().Value())\n\t\t}\n\t\t// check for an error\n\t\tif result.Err() != nil {\n\t\t\tfmt.Printf(\"query parsing error: %s\\n\", result.Err().Error())\n\t\t}\n\t} else {\n\t\tpanic(err)\n\t}\n\t// Ensures background processes finishes\n\tclient.Close()\n}\n```\n\n### Concurrency\nInfluxDB Go Client can be used in a concurrent environment. All its functions are thread-safe.\n\nThe best practise is to use a single `Client` instance per server URL. This ensures optimized resources usage,\nmost importantly reusing HTTP connections.\n\nFor efficient reuse of HTTP resources among multiple clients, create an HTTP client and use `Options.SetHTTPClient()` for setting it to all clients:\n```go\n    // Create HTTP client\n    httpClient := \u0026http.Client{\n        Timeout: time.Second * time.Duration(60),\n        Transport: \u0026http.Transport{\n            DialContext: (\u0026net.Dialer{\n                Timeout: 5 * time.Second,\n            }).DialContext,\n            TLSHandshakeTimeout: 5 * time.Second,\n            TLSClientConfig: \u0026tls.Config{\n                InsecureSkipVerify: true,\n            },\n            MaxIdleConns:        100,\n            MaxIdleConnsPerHost: 100,\n            IdleConnTimeout:     90 * time.Second,\n        },\n    }\n    // Client for server 1\n    client1 := influxdb2.NewClientWithOptions(\"https://server:8086\", \"my-token\", influxdb2.DefaultOptions().SetHTTPClient(httpClient))\n    // Client for server 2\n    client2 := influxdb2.NewClientWithOptions(\"https://server:9999\", \"my-token2\", influxdb2.DefaultOptions().SetHTTPClient(httpClient))\n```\n\nClient 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,\na single `QueryAPI` for each org.\n\nSuch a single API sub-client instance can be used concurrently:\n```go\npackage main\n\nimport (\n\t\"math/rand\"\n\t\"sync\"\n\t\"time\"\n\n\tinfluxdb2 \"github.com/influxdata/influxdb-client-go\"\n\t\"github.com/influxdata/influxdb-client-go/v2/api/write\"\n)\n\nfunc main() {\n    // Create client\n    client := influxdb2.NewClient(\"http://localhost:8086\", \"my-token\")\n    // Ensure closing the client\n    defer client.Close()\n\n    // Get write client\n    writeApi := client.WriteAPI(\"my-org\", \"my-bucket\")\n\n    // Create channel for points feeding\n    pointsCh := make(chan *write.Point, 200)\n\n    threads := 5\n\n    var wg sync.WaitGroup\n    go func(points int) {\n        for i := 0; i \u003c points; i++ {\n            p := influxdb2.NewPoint(\"meas\",\n                map[string]string{\"tag\": \"tagvalue\"},\n                map[string]interface{}{\"val1\": rand.Int63n(1000), \"val2\": rand.Float64()*100.0 - 50.0},\n                time.Now())\n            pointsCh \u003c- p\n        }\n        close(pointsCh)\n    }(1000000)\n\n    // Launch write routines\n    for t := 0; t \u003c threads; t++ {\n        wg.Add(1)\n        go func() {\n            for p := range pointsCh {\n                writeApi.WritePoint(p)\n            }\n            wg.Done()\n        }()\n    }\n    // Wait for writes complete\n    wg.Wait()\n}\n```\n\n### Proxy and redirects\nYou can configure InfluxDB Go client behind a proxy in two ways:\n 1. Using environment variable\n     Set environment variable `HTTP_PROXY` (or `HTTPS_PROXY` based on the scheme of your server url).\n     e.g. (linux) `export HTTP_PROXY=http://my-proxy:8080` or in Go code `os.Setenv(\"HTTP_PROXY\",\"http://my-proxy:8080\")`\n\n 1. Configure `http.Client` to use proxy\u003cbr\u003e\n     Create a custom `http.Client` with a proxy configuration:\n    ```go\n    proxyUrl, err := url.Parse(\"http://my-proxy:8080\")\n    httpClient := \u0026http.Client{\n        Transport: \u0026http.Transport{\n            Proxy: http.ProxyURL(proxyUrl)\n        }\n    }\n    client := influxdb2.NewClientWithOptions(\"http://localhost:8086\", token, influxdb2.DefaultOptions().SetHTTPClient(httpClient))\n    ```\n\n Client automatically follows HTTP redirects. The default redirect policy is to follow up to 10 consecutive requests.\n Due to a security reason _Authorization_ header is not forwarded when redirect leads to a different domain.\n To overcome this limitation you have to set a custom redirect handler:\n```go\ntoken := \"my-token\"\n\nhttpClient := \u0026http.Client{\n    CheckRedirect: func(req *http.Request, via []*http.Request) error {\n        req.Header.Add(\"Authorization\",\"Token \" + token)\n        return nil\n    },\n}\nclient := influxdb2.NewClientWithOptions(\"http://localhost:8086\", token, influxdb2.DefaultOptions().SetHTTPClient(httpClient))\n```\n\n### Checking Server State\nThere are three functions for checking whether a server is up and ready for communication:\n\n| Function| Description | Availability |\n|:----------|:----------|:----------|\n| [Health()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2#Client.Health) | Detailed info about the server status, along with version string | OSS |\n| [Ready()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2#Client.Ready) | Server uptime info | OSS |\n| [Ping()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2#Client.Ping) | Whether a server is up | OSS, Cloud |\n\nOnly the [Ping()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2#Client.Ping) function works in InfluxDB Cloud server.\n\n## InfluxDB 1.8 API compatibility\n\n  [InfluxDB 1.8.0 introduced forward compatibility APIs](https://docs.influxdata.com/influxdb/latest/tools/api/#influxdb-2-0-api-compatibility-endpoints) for InfluxDB 2.0. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.0 Cloud or open source.\n\n  Client API usage differences summary:\n 1. Use the form `username:password` for an **authentication token**. Example: `my-user:my-password`. Use an empty string (`\"\"`) if the server doesn't require authentication.\n 1. The organization parameter is not used. Use an empty string (`\"\"`) where necessary.\n 1. Use the form `database/retention-policy` where a **bucket** is required. Skip retention policy if the default retention policy should be used. Examples: `telegraf/autogen`, `telegraf`.  \n\n  The following forward compatible APIs are available:\n\n  | API | Endpoint | Description |\n  |:----------|:----------|:----------|\n  | [WriteAPI](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#WriteAPI) (also [WriteAPIBlocking](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#WriteAPIBlocking))| [/api/v2/write](https://docs.influxdata.com/influxdb/v2.0/write-data/developer-tools/api/) | Write data to InfluxDB 1.8.0+ using the InfluxDB 2.0 API |\n  | [QueryAPI](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2/api#QueryAPI) | [/api/v2/query](https://docs.influxdata.com/influxdb/v2.0/query-data/execute-queries/influx-api/) | Query data in InfluxDB 1.8.0+ using the InfluxDB 2.0 API and [Flux](https://docs.influxdata.com/flux/latest/) endpoint should be enabled by the [`flux-enabled` option](https://docs.influxdata.com/influxdb/v1.8/administration/config/#flux-enabled-false)\n  | [Health()](https://pkg.go.dev/github.com/influxdata/influxdb-client-go/v2#Client.Health) | [/health](https://docs.influxdata.com/influxdb/v2.0/api/#tag/Health) | Check the health of your InfluxDB instance |\n\n\n### Example\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n\n    \"github.com/influxdata/influxdb-client-go/v2\"\n)\n\nfunc main() {\n    userName := \"my-user\"\n    password := \"my-password\"\n     // Create a new client using an InfluxDB server base URL and an authentication token\n    // For authentication token supply a string in the form: \"username:password\" as a token. Set empty value for an unauthenticated server\n    client := influxdb2.NewClient(\"http://localhost:8086\", fmt.Sprintf(\"%s:%s\",userName, password))\n    // Get the blocking write client\n    // Supply a string in the form database/retention-policy as a bucket. Skip retention policy for the default one, use just a database name (without the slash character)\n    // Org name is not used\n    writeAPI := client.WriteAPIBlocking(\"\", \"test/autogen\")\n    // create point using full params constructor\n    p := influxdb2.NewPoint(\"stat\",\n        map[string]string{\"unit\": \"temperature\"},\n        map[string]interface{}{\"avg\": 24.5, \"max\": 45},\n        time.Now())\n    // Write data\n    err := writeAPI.WritePoint(context.Background(), p)\n    if err != nil {\n        fmt.Printf(\"Write error: %s\\n\", err.Error())\n    }\n\n    // Get query client. Org name is not used\n    queryAPI := client.QueryAPI(\"\")\n    // Supply string in a form database/retention-policy as a bucket. Skip retention policy for the default one, use just a database name (without the slash character)\n    result, err := queryAPI.Query(context.Background(), `from(bucket:\"test\")|\u003e range(start: -1h) |\u003e filter(fn: (r) =\u003e r._measurement == \"stat\")`)\n    if err == nil {\n        for result.Next() {\n            if result.TableChanged() {\n                fmt.Printf(\"table: %s\\n\", result.TableMetadata().String())\n            }\n            fmt.Printf(\"row: %s\\n\", result.Record().String())\n        }\n        if result.Err() != nil {\n            fmt.Printf(\"Query error: %s\\n\", result.Err().Error())\n        }\n    } else {\n        fmt.Printf(\"Query error: %s\\n\", err.Error())\n    }\n    // Close client\n    client.Close()\n}\n```\n\n## Contributing\n\nIf you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the `master` branch.\n\n## License\n\nThe InfluxDB 2 Go Client is released under the [MIT License](https://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finfluxdata%2Finfluxdb-client-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Finfluxdata%2Finfluxdb-client-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finfluxdata%2Finfluxdb-client-go/lists"}