使用gin进行接口。
它的route.go
func Init(api *gin.Engine) {
r := api.Group("/v1")
r.GET("/sites/search/:url", site.Search)
}在控制器文件中,希望使用go-elasticsearch来搜索ES数据。
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),
)
// ...
}当前go-elasticsearch的初始化方法是在一个公共文件中使用ctx context.Context:
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)
// ...
}如果在控制器Search函数中使用req *http.Request,则可以成功调用数据。但是gin的ctx *gin.Context会导致错误:
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我还尝试在GetES函数中使用ctx *gin.Context
func GetES(ctx *gin.Context) bool {或者在ES的搜索方法中设置context.Background():
elasticsearch.ESClient.Search.WithContext(context.Background()),仍然收到错误。
如何将gin和go-elasticsearch与合适的Context类型一起使用?
这个方法需要什么内容?
https://github.com/elastic/go-elasticsearch/blob/master/_examples/main.go#L127
发布于 2020-12-31 14:42:17
*gin.Context与go-elasticsearch询问的上下文不同,如果你在*gin.Context中有搜索词,你可以使用像search()这样的函数来获取和查询它们。
package main
import (
"bytes"
"context"
"encoding/json"
es "github.com/elastic/go-elasticsearch"
api "github.com/elastic/go-elasticsearch/esapi"
app "github.com/gin-gonic/gin"
"io/ioutil"
"log"
"net/http"
"strings"
)
var c *es.Client
func init() {
// connect to elastic search client
cf := es.Config{
Addresses: []string{
"http://localhost:9200",
},
}
e, err := es.NewClient(cf)
if err != nil {
log.Println(err)
}
c = e
// make a new index
// put some new data
// search database for data
}
func search(term string, key string) (by []byte, err error) {
q := map[string]interface{}{
"query": map[string]interface{}{
"match": map[string]interface{}{
key: term},
},
}
var bts bytes.Buffer
if err = json.NewEncoder(&bts).Encode(q); err != nil {
return
}
r, err := c.Search(
c.Search.WithContext(context.Background()),
c.Search.WithIndex("test"),
c.Search.WithBody(&bts),
c.Search.WithTrackTotalHits(true),
c.Search.WithPretty(),
)
if err != nil {
return
}
defer r.Body.Close()
by, err = ioutil.ReadAll(r.Body)
if err != nil || r.StatusCode != http.StatusOK {
return
}
return
}
func handlerr(a interface{}, err error) {
if err != nil {
log.Println(err)
}
log.Printf("%s", a)
}
func main() {
r:=app.Default()
r.GET("/",GetES)
r.Run(":8080")
return
}
func GetES(c *gin.Context){
res, err := search("my experiments with truth", "title")
handlerr(res,err)
c.JSON{http.StatusOK,res}
return
}https://stackoverflow.com/questions/65046350
复制相似问题