In the example shown next, we are going to set up a Go environment to run InfluxDB with Go client.
- Install Go.
Install Go by following the golang installation guide available at:
https://golang.org/doc/install
Set up GOROOT and GOBIN:
sudo apt install golang-go
export GOROOT=/usr/lib/go
export GOBIN=/usr/bin/go
Set up $GOPATH:
mkdir ~/go
export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin
export PATH=$PATH:$GOROOT/bin
Check the Go version:
$ go version
go version go1.6.2 linux/amd64
- Install the InfluxDB Go client library:
go get github.com/InfluxDB/InfluxDB
You should see a message similar to the following:
package github.com/InfluxDB/InfluxDB: code in directory /home/user/go/src/github.com/InfluxDB/InfluxDB expects import "github.com/influxdata/InfluxDB"
- Write the Go program:
package main
import (
"log"
"time"
"github.com/influxdata/InfluxDB/client/v2"
)
const (
database = "testdb"
username = "root"
password = "root"
)
func main() {
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://localhost:8086",
Username: username,
Password: password,
})
// Create a new point batch
bp, err := client.NewBatchPoints(client.BatchPointsConfig{
Database: database,
Precision: "s",
})
// Create a point and add to batch
tags := map[string]string{}
fields1 := map[string]interface{}{
"http": "GET /cgi-bin/try/ HTTP/1.0",
"status": 200,
"duration": 3395,
"ip": "192.168.2.20",
}
pt1, err := client.NewPoint("apachelog_go", tags, fields1, time.Unix(0, 1511361120000000000))
bp.AddPoint(pt1)
fields2 := map[string]interface{}{
"http": "GET / HTTP/1.0",
"status": 200,
"duration": 2216,
"ip": "127.0.0.1",
}
pt2, err := client.NewPoint("apachelog_go", tags, fields2, time.Unix(0, 1511361180000000000))
bp.AddPoint(pt2)
// Write the batch
if err := c.Write(bp); err != nil {
log.Fatal(err)
}
}
}
- Run the Go program as follows:
go run goclientInfluxDBtest.go
Once the program has successfully run, you should see a new measurement—apachelog_go is created in the database and two data points are inserted.
> show measurements
name: measurements
name
----
apachelog_go
apachelog_java
apachelog_py
weather_report
> select * from apachelog_go
name: apachelog_go
time duration http ip status
---- -------- ---- -- ------
2017-11-22T14:32:00Z 3395 GET /cgi-bin/try/ HTTP/1.0 192.168.2.20 200
2017-11-22T14:33:00Z 2216 GET / HTTP/1.0 127.0.0.1 200