tinybird

package module
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 17, 2026 License: GPL-3.0 Imports: 14 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go-Tinybird

A Tinybird module for Go. It provides an easy and standard way of getting data through the Tinybird API.

Features

  • Lightweight and fast. Native Go implementation, no C-bindings.
  • Connection pooling for Tinybird.
  • JSON, NDJSON and CSV response formats.
  • Parallel HTTP requests.
  • Send events to data sources.
  • Read and write values in nested JSON structures using dot-path access.
  • Auto cast string values to their inferred Go types (int64, float64).
  • Custom logic before and after request execution (e.g. caching).
  • Shared logger with logrus.
  • Test your code with mocks.

Requirements

Go 1.24 or higher.

Installation

go get -u github.com/the-hotels-network/go-tinybird

Quickstart

package main

import (
	"fmt"
	"net/http"
	"net/url"
	"os"

	"github.com/the-hotels-network/go-tinybird"
)

func main() {
	params := url.Values{}
	params.Add("start_date", "2022-05-01")
	params.Add("end_date", "2022-05-30")
	params.Add("property_id", "1234")

	req := tinybird.Request{
		Method: http.MethodGet,
		Pipe: tinybird.Pipe{
			Name:       "tinybird_endpoint",
			Parameters: params,
			Workspace: tinybird.Workspace{
				Token: "token-demo",
			},
		},
	}

	err := req.Execute()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	res := req.Response
	fmt.Println("Status:", res.Status)
	fmt.Println("Error:", res.Error)
	fmt.Println("Data:", res.Data)
}

Working with Data

The Data type ([]Row) provides methods to read and write values using dot-separated paths:

res := req.Response

// Get a value by key
val := res.Data.FetchOne("revenue")

// Get a nested value using dot-path
val := res.Data.Get("stats.daily.total")

// Set a value
res.Data.Set("stats.daily.total", 100)

// Set with auto cast (converts numeric strings to int64 or float64)
res.Data.SetWithAutoCast("price", "99.99")   // stores float64(99.99)
res.Data.SetWithAutoCast("count", "42")       // stores int64(42)
res.Data.SetWithAutoCast("label", "hello")    // stores "hello" (unchanged)

The AutoCast function can also be used standalone:

tinybird.AutoCast("42")    // int64(42)
tinybird.AutoCast("3.14")  // float64(3.14)
tinybird.AutoCast("hello") // "hello"
tinybird.AutoCast(99)      // 99 (non-string values pass through)

Parallel Requests

reqs := tinybird.Requests{}

reqs.Add(tinybird.Request{
	Method: http.MethodGet,
	Pipe: tinybird.Pipe{
		Name:      "endpoint_bookings",
		Workspace: tinybird.Workspace{Token: "token-demo"},
	},
})

reqs.Add(tinybird.Request{
	Method: http.MethodGet,
	Pipe: tinybird.Pipe{
		Name:      "endpoint_searches",
		Workspace: tinybird.Workspace{Token: "token-demo"},
	},
})

reqs.Execute()

for _, req := range reqs {
	fmt.Println(req.Response.Data)
}

Events

event := tinybird.Event{
	Method:     http.MethodGet,
	Datasource: "my_datasource",
	Workspace:  tinybird.Workspace{Token: "token-demo"},
}

err := event.Send(map[string]any{"key": "value"})

Response Formats

NDJSON

Set the format on the pipe or via the TB_NDJSON environment variable:

req := tinybird.Request{
	Pipe: tinybird.Pipe{
		Name:   "endpoint",
		Format: tinybird.NDJSON,
	},
}
CSV
req := tinybird.Request{
	Pipe: tinybird.Pipe{
		Name:   "endpoint",
		Format: tinybird.CSV,
	},
}
// Access raw body: req.Response.Body

Before / After Hooks

Add custom logic around request execution, for example a cache layer:

req := tinybird.Request{
	Before: func(r *tinybird.Request) error {
		// Check cache before hitting the API
		return nil
	},
	After: func(r *tinybird.Request) error {
		// Store response in cache
		return nil
	},
}

Configuration

Variable Default Description
tinybird.URL_BASE https://api.tinybird.co Base API URL
tinybird.Client default pool Custom HTTPClient
tinybird.MAX_IDLE_CONNS - Max idle connections
tinybird.MAX_CONNS_PER_HOST - Max connections per host
tinybird.MAX_IDLE_CONNS_PER_HOST - Max idle connections per host
tinybird.CONNS_TIMEOUT - Connection timeout (seconds)

Tests

make tests

More Examples

See the example directory for complete working examples.

Local Development

Point to a local version of the module:

go mod edit -replace github.com/the-hotels-network/go-tinybird=$HOME/go/src/github.com/the-hotels-network/go-tinybird

Revert:

go mod edit -dropreplace github.com/the-hotels-network/go-tinybird
go get -u

Documentation

Index

Constants

View Source
const (
	Format string = "json"
	JSON          = "json"
	NDJSON        = "ndjson"
	CSV           = "csv"
)

Variables

View Source
var CONNS_TIMEOUT int
View Source
var MAX_CONNS_PER_HOST int
View Source
var MAX_IDLE_CONNS int
View Source
var MAX_IDLE_CONNS_PER_HOST int
View Source
var URL_BASE string

Functions

func AutoCast added in v1.6.0

func AutoCast(val any) any

AutoCast attempts to infer the real type of a value. If the value is a string it tries to parse it as int64 first, then float64. Non-string values and strings that cannot be parsed are returned unchanged.

func InjectHTTPClient

func InjectHTTPClient(httpClient *http.Client)

func MockResponse

func MockResponse(statusCode int, body string)

func MockResponseWithRequestInspect

func MockResponseWithRequestInspect(statusCode int, body string, requestInspect func(r *http.Request))

func Version

func Version() string

Version is the current release version.

Types

type Adapter

type Adapter interface {
	Debugf(string, ...interface{})
}

type Data added in v1.5.0

type Data []Row

Data represents a collection (slice) of rows returned from a query or dataset.

func (Data) FetchOne added in v1.5.0

func (d Data) FetchOne(in string) (out any)

FetchOne retrieves the value of a specific field from the first Row in the Data slice, using the provided field name (key). If the key doesn't exist, it returns nil.

func (Data) First added in v1.5.0

func (d Data) First() Row

First returns the first Row in the Data slice. It assumes the slice is not empty.

func (Data) Get added in v1.6.0

func (d Data) Get(in string) any

Get retrieves a value from the first row of the Data structure by traversing a dot-separated path.

The path represents nested keys within Row maps (e.g. "a.b.c"). If the Data slice is empty, the path does not exist, or an intermediate value is not a Row, Get returns nil.

func (Data) Len added in v1.5.1

func (d Data) Len() int

Count the items.

func (*Data) Set added in v1.6.0

func (d *Data) Set(in string, value any) error

Set assigns a value in the first row of the Data structure at the location specified by a dot-separated path.

Intermediate Row nodes are created as needed if they do not exist. An error is returned if Data is empty, the path is empty, or a non-Row value is encountered while traversing the path.

func (*Data) SetWithAutoCast added in v1.6.0

func (d *Data) SetWithAutoCast(in string, value any) error

SetWithAutoCast works like Set but applies AutoCast to the value before storing it, converting numeric strings to their int64 or float64 equivalents.

func (Data) ToString added in v1.5.0

func (d Data) ToString() (out string)

ToString converts the entire Data slice into a JSON-formatted string. If marshalling fails, it returns an empty string.

type Duration

type Duration time.Duration

func (*Duration) Do

func (d *Duration) Do(fn func() error) error

Calculate child function duration.

func (Duration) Seconds

func (d Duration) Seconds() string

Convert duration to seconds unit.

type Event added in v1.4.0

type Event struct {
	Name       string
	Datasource string
	Workspace  Workspace
}

func (Event) GetURI added in v1.4.0

func (e Event) GetURI() string

func (Event) GetURL added in v1.4.0

func (e Event) GetURL() string

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient interface.

var Client HTTPClient

Custom HTTP client for this module.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(a Adapter) Logger

func (*Logger) Debugf

func (l *Logger) Debugf(fmt string, args ...interface{})

type LogrusAdapter

type LogrusAdapter struct{}

func (LogrusAdapter) Debugf

func (l LogrusAdapter) Debugf(fmt string, args ...interface{})

type Meta

type Meta struct {
	Name string `json:"name,omitempty"`
	Type string `json:"type,omitempty"`
}

Specific field with data type.

type MockRoundTripper

type MockRoundTripper func(r *http.Request) *http.Response

func (MockRoundTripper) RoundTrip

func (f MockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error)

type Pipe

type Pipe struct {
	// Name of pipe. Define by user.
	Name string
	// Alias of pipe. Optional.
	Alias string
	// Is for internal purpose and is generated by code.
	URL string
	// Parameters use on pipe. Define by user.
	Parameters url.Values
	// Is an area that contains a set of Tinybird resources, including Pipes,
	// Nodes, APIs, Data Sources & Auth Tokens. Define by user.
	Workspace Workspace
	// Return format.
	Format string
}

Pipe is a object on tinybird, contains one or more SQL queries (Nodes) that result in either an API endpoint or a Materialized View.

func (Pipe) GetFormat added in v1.4.0

func (p Pipe) GetFormat() string

Verify the variable Format value to return json, ndjson or csv.

func (*Pipe) GetParameters

func (p *Pipe) GetParameters() string

func (Pipe) GetURI added in v1.4.0

func (p Pipe) GetURI() string

func (Pipe) GetURL added in v1.4.0

func (p Pipe) GetURL() string

Build and return the pipe URL.

type Request

type Request struct {
	After    func(*Request)      // Run after execute request.
	Before   func(*Request) bool // Run before execute request.
	Data     []byte              // Data to send.
	Elapsed  Duration            // Elapsed time of client request.
	Error    error               // Error on client request.
	Event    Event               // Send event to data source.
	Method   string              // Define HTTP method.
	Pipe     Pipe                // Pipe details.
	Response Response            // Response data.
}

Basic request struct.

func (*Request) Execute

func (r *Request) Execute() error

Execute request.

func (*Request) Format

func (r *Request) Format() (out string)

func (*Request) Token added in v1.4.0

func (r *Request) Token() (out string)

func (*Request) URI

func (r *Request) URI() (out string)

func (*Request) URL

func (r *Request) URL() (out string)

type Requests

type Requests []Request

Slice for all request to execute in parallel.

func (*Requests) Add

func (rs *Requests) Add(i Request)

Add request into slice.

func (Requests) Duration

func (rs Requests) Duration() Duration

Return elapsed time for all requests.

func (*Requests) Execute

func (rs *Requests) Execute()

Execute multithreading/parallel request.

func (*Requests) Get

func (rs *Requests) Get(workspace, pipe string) Request

Recover specific request by pipe.

func (*Requests) GetByAlias

func (rs *Requests) GetByAlias(workspace, pipe, alias string) Request

type Response

type Response struct {
	Cached                 bool          // Flag control to use to determine the origin this response.
	Raw                    io.ReadCloser // Raw is the original data from response.
	Body                   string        // Body in string format, same a Data but in struct format and Raw in original format.
	Data                   Data          `json:"data,omitempty"`                       // Data is part a tinybird response.
	Documentation          string        `json:"documentation,omitempty"`              // Documentation is part a tinybird response.
	Error                  string        `json:"error,omitempty"`                      // Error is part a tinybird response.
	Meta                   []Meta        `json:"meta,omitempty"`                       // Meta is part a tinybird response.
	Rows                   uint          `json:"rows,omitempty"`                       // Rows is part a tinybird response.
	RowsBeforeLimitAtLeast uint          `json:"rows_before_limit_at_least,omitempty"` // RowsBeforeLimitAtLeast is part a tinybird response.
	Statistics             Statistics    `json:"statistics,omitempty"`                 // Statistics is part a tinybird response.
	Status                 int           // Status is a HTTP status code, ej: 200, 400, 500 etc...
	Header                 http.Header   // Headers contains the HTTP response headers returned by the server
	Format                 string        // Save format setting.
	SuccessfulRows         int           `json:"successful_rows"`
	QuarantinedRows        int           `json:"quarantined_rows"`
}

Basic JSON struct for all response by Tinybird.

func (*Response) CSV

func (r *Response) CSV() error

Convert body to CSV.

func (*Response) Decode

func (r *Response) Decode() (err error)

Convert response body to struct.

func (*Response) JSON

func (r *Response) JSON() error

Convert body to JSON.

func (*Response) NDJSON

func (r *Response) NDJSON() error

Convert body to NDJSON.

type Row

type Row map[string]any

Row is a generic map-based structure that can hold fields of any type. Each key corresponds to a field name, and each value can be any Go type.

type Statistics

type Statistics struct {
	Elapsed   float64 `json:"elapsed,omitempty"`
	RowsRead  uint64  `json:"rows_read,omitempty"`
	BytesRead uint64  `json:"bytes_read,omitempty"`
}

Statistics information about the response.

type Workspace

type Workspace struct {
	// Workspace name:
	Name string
	// Each workspace have individual token:
	Token string
}

Each workspace has a name and token.

func (*Workspace) GetToken added in v1.4.0

func (w *Workspace) GetToken() string

func (*Workspace) IsSet added in v1.4.0

func (w *Workspace) IsSet() bool

Directories

Path Synopsis
example
request module
internal
env

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址