golang: client declared and not used

0

I'm doing tests with the go library for elasticsearch: link

I have the following code that is my library to connect to the Elasticsearch server:

package elasticsearch

import (
    "fmt"
    "os"
    elastic "gopkg.in/olivere/elastic.v5"
    "context"
)

var client *elastic.Client

func init() {

    var err error

    client, err := elastic.NewClient(
        elastic.SetURL(os.Getenv("ELASTICSEARCH_ENTRYPOINT")),
        elastic.SetBasicAuth(os.Getenv("ELASTICSEARCH_USERNAME"), os.Getenv("ELASTICSEARCH_PASSWORD")),
    )
    if err != nil {
        panic(err)
    }

}

func Ping() (string, error) {

    ctx := context.Background()
    info, code, err := client.Ping(os.Getenv("ELASTICSEARCH_ENTRYPOINT")).Do(ctx)
    if err != nil {
        panic(err)
    }
    msg := fmt.Sprintf("Elasticsearch returned with code %d and version %s", code, info.Version.Number)
    return msg, nil

}

And my main program is as follows:

package main

import (
    "fmt"
    _ "github.com/hectorgool/gomicrosearch3/elasticsearch"
)

func main() {

    if result, err := elasticsearch.Ping(); err != nil {
        fmt.Printf("Error: %s\n", err)
    } else {
        fmt.Printf("ElasticSearch result: '%s'\n", result)
    }

}

But when you run the program with:

go run main.go

It shows me the following:

elasticsearch / elasticsearch.go: 18: client declared and not used

Line 18 corresponds to the following block of code:

client, err := elastic.NewClient(
    elastic.SetURL(os.Getenv("ELASTICSEARCH_ENTRYPOINT")),
    elastic.SetBasicAuth(os.Getenv("ELASTICSEARCH_USERNAME"), os.Getenv("ELASTICSEARCH_PASSWORD")),
)

Someone can tell me what the program is missing or what I am doing wrong.

    
asked by Sanx 20.08.2017 в 00:39
source

2 answers

1

The error that the compiler is notifying you is because you are declaring a variable that you are not using, in this case client . Remember that in Go you can not define variables if they are not used later.

Although you have defined client with package scope, in the function init you have used the operator: = to define a new variable client , in this case with local scope, and this has been superimposed on the global client variable, so when the execution of the function finishes, the Go compiler detects that the variable has not been used > client local.

    
answered by 22.08.2017 в 18:16
0

If you are only going to use the value of err and not the client you have to replace client with "_", that is

_, err := elastic.NewClient(
    elastic.SetURL(os.Getenv("ELASTICSEARCH_ENTRYPOINT")),
    elastic.SetBasicAuth(os.Getenv("ELASTICSEARCH_USERNAME"), 
os.Getenv("ELASTICSEARCH_PASSWORD")),
)
    
answered by 19.12.2017 в 13:50