How to use go-elasticsearch library with gin framework?

Using gin for API.

Its route.go

func Init(api *gin.Engine) {
    r := api.Group("/v1")
    r.GET("/sites/search/:url", site.Search)
}

In the controller file, want to use go-elasticsearch for searching ES data.

import (
    "context"
    "github.com/myapp/common/elasticsearch"
)

func Search(ctx *gin.Context) {
   var data bool
   data = GetES(ctx.Request.Context()) 
}

func GetES(ctx context.Context) bool {
    var (
        r   map[string]interface{}
        buf bytes.Buffer
    )

    var buf bytes.Buffer
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"title": "test",
			},
		},
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}


    res, err := elasticsearch.ESClient.Search(
        elasticsearch.ESClient.Search.WithContext(ctx),
        elasticsearch.ESClient.Search.WithIndex("indexname"),
        elasticsearch.ESClient.Search.WithBody(&buf),
        elasticsearch.ESClient.Search.WithTrackTotalHits(true),
    )
    // ...
}

The current go-elasticsearch's initialize method is using ctx context.Context in a common file:

import (
    "context"
    elasticsearch "github.com/elastic/go-elasticsearch/v8"
    "github.com/elastic/go-elasticsearch/v8/esapi"
)

func Init(ctx context.Context) {
    var (
        ESClient = *elasticsearch.Client
    )
    // ...
    res, err := esapi.InfoRequest{}.Do(ctx, ESClient)
    // ...
}

If use req *http.Request in the controller Search function, it's possible to call data successfully. But gin's ctx *gin.Context will cause error:

runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:199 (0x44470b)
	panicmem: panic(memoryError)
/usr/local/go/src/runtime/signal_unix.go:394 (0x444548)
	sigpanic: panicmem()
/application/site/controller.go:100 (0xe9afea)
	GetES: elasticsearch.ESClient.Search.WithContext(ctx),
/application/site/controller.go:77 (0xe9a8a4)
	Search: data = GetES(ctx.Request.Context())
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
	(*Context).Next: c.handlers[c.index](c)
/app/service/console/application/golang/console-api/application/auth/authenticate.go:16 (0xb90f7a)
	APIKeyAuthenticate.func1: ctx.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
	(*Context).Next: c.handlers[c.index](c)
/app/service/console/application/golang/console-api/application/error/error_handler.go:13 (0xb3c60e)
	Handle500.func1: ctx.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
	(*Context).Next: c.handlers[c.index](c)
/app/service/console/application/golang/console-api/application/error/error_handler.go:27 (0xb3c84f)
	Handle400.func1: ctx.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
	(*Context).Next: c.handlers[c.index](c)
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/recovery.go:83 (0x99bad3)
	RecoveryWithWriter.func1: c.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
	(*Context).Next: c.handlers[c.index](c)
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/logger.go:241 (0x99ac00)
	LoggerWithConfig.func1: c.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x987fda)
	(*Context).Next: c.handlers[c.index](c)
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:409 (0x991f1c)
	(*Engine).handleHTTPRequest: c.Next()
/go/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:367 (0x99161d)
	(*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/go/src/net/http/server.go:2802 (0x6dc303)
	serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/net/http/server.go:1890 (0x6d7ba4)
	(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/runtime/asm_amd64.s:1357 (0x45d300)
	goexit: BYTE	$0x90	// NOP

I also tried to use ctx *gin.Context in the GetES function

func GetES(ctx *gin.Context) bool {

or set context.Background() in the ES's search method:

elasticsearch.ESClient.Search.WithContext(context.Background()),

Still got the error.

How to use gin with go-elasticsearch together with a suitable Context type?

What content it needs in this method?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.