github.com/mundipagg/boleto-api@v0.0.0-20230620145841-3f9ec742599f/db/elastic.go (about) 1 package db 2 3 import ( 4 "net/http" 5 "strings" 6 7 "fmt" 8 9 "io/ioutil" 10 11 "encoding/json" 12 13 "github.com/mundipagg/boleto-api/config" 14 "github.com/mundipagg/boleto-api/models" 15 "github.com/mundipagg/boleto-api/util" 16 ) 17 18 type elasticDb struct{} 19 20 //SaveBoleto salva um boleto no elasticsearch 21 func (e *elasticDb) SaveBoleto(boleto models.BoletoView) error { 22 client := util.DefaultHTTPClient() 23 url := fmt.Sprintf("%s/boletoapi/boleto/%s", config.Get().ElasticURL, boleto.ID) 24 req, err := http.NewRequest("POST", url, strings.NewReader(boleto.ToJSON())) 25 if err != nil { 26 return err 27 } 28 resp, errResp := client.Do(req) 29 if errResp != nil { 30 return errResp 31 } 32 defer req.Body.Close() 33 defer resp.Body.Close() 34 return nil 35 } 36 37 //GetBoletoById busca um boleto pelo ID que vem na URL 38 func (e *elasticDb) GetBoletoByID(id string) (models.BoletoView, error) { 39 client := util.DefaultHTTPClient() 40 url := fmt.Sprintf("%s/boletoapi/boleto/%s", config.Get().ElasticURL, id) 41 req, err := http.NewRequest("GET", url, nil) 42 if err != nil { 43 return models.BoletoView{}, err 44 } 45 resp, errResp := client.Do(req) 46 if errResp != nil { 47 return models.BoletoView{}, errResp 48 } 49 defer resp.Body.Close() 50 51 data, _ := ioutil.ReadAll(resp.Body) 52 53 elasticData := struct { 54 Source models.BoletoView `json:"_source"` 55 }{} 56 json.Unmarshal(data, &elasticData) 57 return elasticData.Source, nil 58 } 59 60 func (e *elasticDb) Close() {}