package i2es import ( "bytes" "encoding/json" "errors" "io/ioutil" "net/http" "strings" ) // ESDoc Elasticsearch document structure type ESDoc struct { Echo string `json:"echo"` Subg string `json:"subg"` To string `json:"to"` Author string `json:"author"` Message string `json:"message"` Date string `json:"date"` MsgID string `json:"msgid"` } // ESConf ES connection settings type ESConf struct { Host string Index string Type string } // PutToIndex ... func (es ESConf) PutToIndex(msg ESDoc) error { putURI := strings.Join([]string{es.Host, es.Index, es.Type, msg.MsgID}, "/") doc, err := json.Marshal(msg) if err != nil { return err } req, err := http.NewRequest("PUT", putURI, bytes.NewBuffer(doc)) client := &http.Client{} resp, err := client.Do(req) defer resp.Body.Close() return err } // ESRes ES response minimal structure type ESRes struct { Took int `json:"took"` TimedOut bool `json:"timed_out"` Hits Hits `json:"hits"` } // Hits ... type Hits struct { Total int `json:"total"` MaxScore float32 `json:"max_score"` Hits []interface{} `json:"hits"` } // CheckID ... func (es ESConf) CheckID(id string) (bool, error) { searchURI := strings.Join([]string{es.Host, es.Index, es.Type, "_search"}, "/") searchQ := strings.Join([]string{`{"query": {"match": {"_id": "`, id, `"}}}`}, "") req, err := http.NewRequest("POST", searchURI, bytes.NewBuffer([]byte(searchQ))) client := &http.Client{} resp, err := client.Do(req) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return false, err } var e ESRes err = json.Unmarshal(body, &e) if err != nil { return false, err } if e.Hits.Total > 0 { err = errors.New(strings.Join([]string{"Message ", id, " already in index"}, "")) return false, err } if e.TimedOut { err = errors.New("Request time out") return false, err } return false, nil }