How can I use methods of function arguments?
func writeToInflux(c interface{}, host string, service string, state string) bool {
fmt.Println(reflect.TypeOf(c), host, service)
bp, e := client.NewBatchPoints(client.BatchPointsConfig{
Database: database,
Precision: "us",
})
if e != nil {
log.Print(e)
}
tags := map[string]string{
"host": host,
"service": service,
}
fields := map[string]interface{}{
"state": state,
}
pt, err := client.NewPoint("mon", tags, fields, time.Now())
if err != nil {
log.Print(err)
}
bp.AddPoint(pt)
if err := c.Write(bp); err != nil {
log.Print("write failed " + err)
}
return true
}
func handler(w http.ResponseWriter, r *http.Request) {
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: "http://10.x.x.x:8086",
Username: username,
Password: password,
})
if err != nil {
log.Print(err)
}
a := strings.Split(r.URL.Path, "/")
writeToInflux(c, a[3], a[4], a[5])
}
In this example i can't use parameters of c variable, or maybe there is another options to use c as parameter to function?
"c" is an interface{} type, Having an interface in function parameter, you can able to pass any struct or any data types into it.
In your case you want c to use the function write
if err := c.Write(bp); err != nil {
log.Print("write failed " + err)
}
The compiler doesn't know the type of c, so you need to type assert it.
Try this, It will work
newC,ok:= c.(type of c) type of C -> a struct or any type which has a method write
if ok {
if err := newC.Write(bp); err != nil {
log.Print("write failed " + err)
}
}
Or Change your function like this
func writeToInflux(c client.Client, host string, service string, state string) bool
In writeToInflux
, the c interface{}
doesn't specify any methods c
should implement. You should use sine InfluxWriter
interface so you can call c.Write
:
type InfluxWriter {
Write(bp client.BatchPoints) (*client.Response, error)
}
Alternatively, writeToInflux
can accept a client.Client
, giving you access to all its methods.