我正在Go中开发一个中间件,它拦截HTTP请求,从请求正文中读取SON数据,并将其作为Elasticsearch中基于this documentation的文档进行索引.
然而,尽管该文档似乎在Elasticsearch中进行了索引,但该过程返回了Invalid JSON format: EOF
错误.此错误阻止中间件继续执行其他数据库操作的主处理程序.
以下是我的中间件代码的相关部分:
package middlewares
import (
"encoding/json"
"net/http"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
"github.com/google/uuid"
)
// IndexDocumentMiddleware creates a middleware to index documents into Elasticsearch
func IndexDocumentMiddleware(es *elasticsearch.TypedClient) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Read and decode the request body into a generic map to determine the type of document
var doc map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&doc); err != nil {
http.Error(w, "Error parsing request body", http.StatusBadRequest)
return
}
var indexName string
if typeName, ok := doc["type"].(string); ok {
indexName = typeName
} else {
http.Error(w, "Error: 'type' is not a string or is missing", http.StatusBadRequest)
return
}
existsRes, err := es.Indices.Exists(indexName).Do(ctx)
if err != nil {
http.Error(w, "Error existsRes: "+err.Error(), http.StatusInternalServerError)
return
}
if !existsRes {
_, err := es.Indices.Create(indexName).Mappings(types.NewTypeMapping()).Do(ctx)
if err != nil {
http.Error(w, "Error creating index: "+err.Error(), http.StatusInternalServerError)
return
}
}
docID := uuid.New().String()
_, err = es.Index(indexName).
Id(docID).
Document(doc).Do(ctx)
if err != nil {
http.Error(w, "Error indexing document: "+err.Error(), http.StatusInternalServerError)
return
}
next.ServeHTTP(w, r)
})
}
}
Incredit req / res
关于基巴纳的文件
具体问题:
- 尽管文档似乎已成功编制索引,但是什么导致"无效的SON格式:格式"错误?
- 如何确保正确处理SON数据并且没有返回错误,以便中间件可以继续到主处理程序?
如果有任何见解或建议来解决这个问题,我们将不胜感激!