dimanche 10 juillet 2016

How to use an un exported object from third party package as return type in golang?

In my use case I am using influxdb. I am trying to create a global client to influxdb in golang. But when I return the influxdb client from a function, the client object is not exported in the influxdb golang package. So I am not able to return this.

Here is my code,

package influxclient

import (
    "http://ift.tt/29H8YOb"
    "log"
    "time"
    //"net/http"
    "fmt"
    "reflect"
)

const (
    INFLUXDB_NAME = "XXXX"
    USERNAME      = "YYYY"
    PASSWORD      = "ZZZZ"
    HOST          = "http://localhost:8086"
)

var (
    c             = getHTTPClient()
)

func test() {
    // Create a new point batch
    bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
        Database:  INFLUXDB_NAME,
        Precision: "s",
    })

    // Create a point and add to batch
    tags := map[string]string{"cpu": "cpu-total"}
    fields := map[string]interface{}{
        "idle":   10.1,
        "system": 53.3,
        "user":   46.6,
    }
    fmt.Println(reflect.TypeOf(c))
    pt, _ := client.NewPoint("cpu_usage", tags, fields, time.Now())
    bp.AddPoint(pt)

    // Write the batch
    c.Write(bp)
}

//publish metrics to metrics db
func PublishMetrics(metricName string, tags map[string]string, fields map[string]interface{}, time time.Time) error {
    fmt.Println("type of client c ", reflect.TypeOf(c))
    // Create a new point batch
    bp, err := client.NewBatchPoints(client.BatchPointsConfig{
        Database:  INFLUXDB_NAME,
        Precision: "s",
    })
    if err != nil {
        return err
    }
    pt, err := client.NewPoint(metricName, tags, fields, time)
    if err != nil {
        return err
    }
    bp.AddPoint(pt)
    // Write the batch
    c.Write(bp)
    return nil
}


func getHTTPClient() *client.client {
    //make http client for metrics db
    c, err := client.NewHTTPClient(client.HTTPConfig{
        Addr:     HOST,
        Username: USERNAME,
        Password: PASSWORD,
    })
    if err != nil {
        log.Printf("FATAL :: Error occured in getting influxdb metric client %s ", err.Error())
    }
    return c
}

getHTTPClient() function is trying to return the client object *client.client. But the client object is not exported in influxdb golang package. So how can I handle this problem? Could anyone help me with this?

Thanks





Aucun commentaire:

Enregistrer un commentaire