消除错误处理

This commit is contained in:
2023-11-30 04:10:21 +08:00
parent ffa12e09cb
commit c894a6ee9f
2 changed files with 13 additions and 19 deletions

View File

@@ -301,22 +301,9 @@ func main() {
}
var conditions strings.Builder
// 如果是查询 text, 直接从 Elasticsearch 返回结果
var text_ids []int
var text_ids []string
if text := QueryConditions("text"); len(text) > 0 {
rest := models.ElasticsearchSearch(strings.Join(text, " "))
if rest == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for _, hit := range rest["hits"].(map[string]interface{})["hits"].([]interface{}) {
id, err := strconv.Atoi(hit.(map[string]interface{})["_id"].(string))
if err != nil {
log.Println("strconv.Atoi failed:", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
text_ids = append(text_ids, id)
}
text_ids := models.ElasticsearchSearch(strings.Join(text, " ")).GetIDList()
if len(text_ids) > 0 {
conditions.WriteString(fmt.Sprintf(" WHERE id IN (%s)", strings.Trim(strings.Replace(fmt.Sprint(text_ids), " ", ",", -1), "[]")))
} else {

View File

@@ -56,6 +56,13 @@ type SearchData struct {
took int
}
func (sd *SearchData) GetIDList() (id_list []string) {
for _, hit := range sd.Hits.Hits {
id_list = append(id_list, hit.ID)
}
return id_list
}
func ElasticsearchSearch(text string) (r *SearchData) {
// 通过字符串构建查询
var buf bytes.Buffer
@@ -68,7 +75,7 @@ func ElasticsearchSearch(text string) (r *SearchData) {
}
if err := json.NewEncoder(&buf).Encode(query); err != nil {
log.Printf("Error encoding query: %s", err)
return nil
return
}
es := elasticsearch_init()
@@ -83,20 +90,20 @@ func ElasticsearchSearch(text string) (r *SearchData) {
)
if err != nil {
log.Printf("Error getting response: %s", err)
return nil
return
}
defer res.Body.Close()
// 处理错误
if res.IsError() {
log.Printf("Error: %s", res.String())
return nil
return
}
// 转换返回结果
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Printf("Error parsing the response body: %s", err)
return nil
return
}
return r