Client in Go
Query
GET
Make a SQL query with URL escaping.
q := url.QueryEscape("select count(*) from M$SYS_TABLES where name = 'TAGDATA'")
Call HTTP GET method.
|
|
POST JSON
A client can request a JSON message containing a SQL query.
Make JSON content with a SQL query.
|
|
Call HTTP POST method with the Content-type.
|
|
Full source code
|
|
POST FormData
It is possible to send SQL query from HTML form data.
data := url.Values{"q": {"select count(*) from M$SYS_TABLES where name = 'TAGDATA'"}}
rsp, err := client.Post(addr, "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode()))
Full source code
|
|
Write
POST JSON
|
|
POST CSV
|
|
Example
CREATE TAG TABLE IF NOT EXISTS EXAMPLE (
NAME VARCHAR(20) PRIMARY KEY,
TIME DATETIME BASETIME,
VALUE DOUBLE SUMMARIZED
);
If you are a Go programmer and prefer to write RESTful API client, this is the way to go.
Code explains
Define data structure that represents the payload of write API.
type WriteReq struct {
Table string `json:"table"`
Data WriteReqData `json:"data"`
}
type WriteReqData struct {
Columns []string `json:"columns"`
Rows [][]any `json:"rows"`
}
The API for writing data via HTTP is explained in here and it expects to receive JSON payload.
We can prepare payload like below code, so that write multiple records within a payload.
Assume sin
, cos
variables are properly initialized float64
values.
content, _ := json.Marshal(&WriteReq{
Data: WriteReqData{
Columns: []string{"name", "time", "value"},
Rows: [][]any{
{"wave.sin", ts.UTC().UnixNano(), sin},
{"wave.cos", ts.UTC().UnixNano(), cos},
},
},
})
It will be encoded as JSON for writing API like below.
{
"data": {
"columns":["name", "time", "value"],
"rows": [
[ "wave.sin", 1670380342000000000, 1.1 ],
[ "wave.cos", 1670380343000000000, 2.2 ]
]
}
}
Send it to server via http POST request.
client := http.Client{}
rsp, err := client.Post("http://127.0.0.1:5654/db/write/EXAMPLE",
"application/json", bytes.NewBuffer(content))
Server replies HTTP 200 OK
if it successfully writes data.
Full source code
package main
import (
"bytes"
"encoding/json"
"fmt"
"math"
"net/http"
"time"
)
type WriteReq struct {
Table string `json:"table"`
Data WriteReqData `json:"data"`
}
type WriteReqData struct {
Columns []string `json:"columns"`
Rows [][]any `json:"rows"`
}
func main() {
client := http.Client{}
for ts := range time.Tick(500 * time.Millisecond) {
delta := float64(ts.UnixMilli()%15000) / 15000
theta := 2 * math.Pi * delta
sin, cos := math.Sin(theta), math.Cos(theta)
content, _ := json.Marshal(&WriteReq{
Table: "EXAMPLE",
Data: WriteReqData{
Columns: []string{"name", "time", "value"},
Rows: [][]any{
{"wave.sin", ts.UTC().UnixNano(), sin},
{"wave.cos", ts.UTC().UnixNano(), cos},
},
},
})
rsp, err := client.Post(
"http://127.0.0.1:5654/db/write/example",
"application/json",
bytes.NewBuffer(content))
if err != nil {
panic(err)
}
if rsp.StatusCode != http.StatusOK {
panic(fmt.Errorf("response %d", rsp.StatusCode))
}
}
}